1 /*
2 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
3 %                                                                             %
4 %                                                                             %
5 %                                                                             %
6 %                     V   V  IIIII   CCCC   AAA   RRRR                        %
7 %                     V   V    I    C      A   A  R   R                       %
8 %                     V   V    I    C      AAAAA  RRRR                        %
9 %                      V V     I    C      A   A  R R                         %
10 %                       V    IIIII   CCCC  A   A  R  R                        %
11 %                                                                             %
12 %                                                                             %
13 %                    Read/Write VICAR Rasterfile Format                       %
14 %                                                                             %
15 %                              Software Design                                %
16 %                                   Cristy                                    %
17 %                                 July 1992                                   %
18 %                                                                             %
19 %                                                                             %
20 %  Copyright 1999-2021 ImageMagick Studio LLC, a non-profit organization      %
21 %  dedicated to making software imaging solutions freely available.           %
22 %                                                                             %
23 %  You may not use this file except in compliance with the License.  You may  %
24 %  obtain a copy of the License at                                            %
25 %                                                                             %
26 %    https://imagemagick.org/script/license.php                               %
27 %                                                                             %
28 %  Unless required by applicable law or agreed to in writing, software        %
29 %  distributed under the License is distributed on an "AS IS" BASIS,          %
30 %  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.   %
31 %  See the License for the specific language governing permissions and        %
32 %  limitations under the License.                                             %
33 %                                                                             %
34 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
35 %
36 %
37 */
38 
39 /*
40   Include declarations.
41 */
42 #include "MagickCore/studio.h"
43 #include "MagickCore/attribute.h"
44 #include "MagickCore/blob.h"
45 #include "MagickCore/blob-private.h"
46 #include "MagickCore/cache.h"
47 #include "MagickCore/colormap.h"
48 #include "MagickCore/colorspace.h"
49 #include "MagickCore/colorspace-private.h"
50 #include "MagickCore/constitute.h"
51 #include "MagickCore/exception.h"
52 #include "MagickCore/exception-private.h"
53 #include "MagickCore/image.h"
54 #include "MagickCore/image-private.h"
55 #include "MagickCore/list.h"
56 #include "MagickCore/magick.h"
57 #include "MagickCore/memory_.h"
58 #include "MagickCore/module.h"
59 #include "MagickCore/monitor.h"
60 #include "MagickCore/monitor-private.h"
61 #include "MagickCore/quantum-private.h"
62 #include "MagickCore/quantum-private.h"
63 #include "MagickCore/static.h"
64 #include "MagickCore/string_.h"
65 #include "MagickCore/string-private.h"
66 
67 /*
68   Forward declarations.
69 */
70 static MagickBooleanType
71   WriteVICARImage(const ImageInfo *,Image *,ExceptionInfo *);
72 
73 /*
74 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
75 %                                                                             %
76 %                                                                             %
77 %                                                                             %
78 %   I s V I C A R                                                             %
79 %                                                                             %
80 %                                                                             %
81 %                                                                             %
82 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
83 %
84 %  IsVICAR() returns MagickTrue if the image format type, identified by the
85 %  magick string, is VICAR.
86 %
87 %  The format of the IsVICAR method is:
88 %
89 %      MagickBooleanType IsVICAR(const unsigned char *magick,
90 %        const size_t length)
91 %
92 %  A description of each parameter follows:
93 %
94 %    o magick: compare image format pattern against these bytes.
95 %
96 %    o length: Specifies the length of the magick string.
97 %
98 */
IsVICAR(const unsigned char * magick,const size_t length)99 static MagickBooleanType IsVICAR(const unsigned char *magick,
100   const size_t length)
101 {
102   if (length < 14)
103     return(MagickFalse);
104   if (LocaleNCompare((const char *) magick,"LBLSIZE",7) == 0)
105     return(MagickTrue);
106   if (LocaleNCompare((const char *) magick,"NJPL1I",6) == 0)
107     return(MagickTrue);
108   if (LocaleNCompare((const char *) magick,"PDS_VERSION_ID",14) == 0)
109     return(MagickTrue);
110   return(MagickFalse);
111 }
112 
113 /*
114 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
115 %                                                                             %
116 %                                                                             %
117 %                                                                             %
118 %   R e a d V I C A R I m a g e                                               %
119 %                                                                             %
120 %                                                                             %
121 %                                                                             %
122 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
123 %
124 %  ReadVICARImage() reads a VICAR image file and returns it.  It
125 %  allocates the memory necessary for the new Image structure and returns a
126 %  pointer to the new image.
127 %
128 %  The format of the ReadVICARImage method is:
129 %
130 %      Image *ReadVICARImage(const ImageInfo *image_info,
131 %        ExceptionInfo *exception)
132 %
133 %  A description of each parameter follows:
134 %
135 %    o image: Method ReadVICARImage returns a pointer to the image after
136 %      reading.  A null image is returned if there is a memory shortage or if
137 %      the image cannot be read.
138 %
139 %    o image_info: the image info.
140 %
141 %    o exception: return any errors or warnings in this structure.
142 %
143 %
144 */
ReadVICARImage(const ImageInfo * image_info,ExceptionInfo * exception)145 static Image *ReadVICARImage(const ImageInfo *image_info,
146   ExceptionInfo *exception)
147 {
148   char
149     keyword[MagickPathExtent],
150     value[MagickPathExtent];
151 
152   Image
153     *image;
154 
155   int
156     c;
157 
158   MagickBooleanType
159     status,
160     value_expected;
161 
162   QuantumInfo
163     *quantum_info;
164 
165   QuantumType
166     quantum_type;
167 
168   Quantum
169     *q;
170 
171   size_t
172     length;
173 
174   ssize_t
175     count,
176     y;
177 
178   unsigned char
179     *pixels;
180 
181   /*
182     Open image file.
183   */
184   assert(image_info != (const ImageInfo *) NULL);
185   assert(image_info->signature == MagickCoreSignature);
186   if (image_info->debug != MagickFalse)
187     (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",
188       image_info->filename);
189   assert(exception != (ExceptionInfo *) NULL);
190   assert(exception->signature == MagickCoreSignature);
191   image=AcquireImage(image_info,exception);
192   status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception);
193   if (status == MagickFalse)
194     {
195       image=DestroyImageList(image);
196       return((Image *) NULL);
197     }
198   /*
199     Decode image header.
200   */
201   c=ReadBlobByte(image);
202   count=1;
203   if (c == EOF)
204     {
205       image=DestroyImage(image);
206       return((Image *) NULL);
207     }
208   length=0;
209   image->columns=0;
210   image->rows=0;
211   while (isgraph((int) ((unsigned char) c)) && ((image->columns == 0) || (image->rows == 0)))
212   {
213     if (isalnum((int) ((unsigned char) c)) == MagickFalse)
214       {
215         c=ReadBlobByte(image);
216         count++;
217       }
218     else
219       {
220         char
221           *p;
222 
223         /*
224           Determine a keyword and its value.
225         */
226         p=keyword;
227         do
228         {
229           if ((size_t) (p-keyword) < (MagickPathExtent-1))
230             *p++=c;
231           c=ReadBlobByte(image);
232           count++;
233         } while (isalnum((int) ((unsigned char) c)) || (c == '_'));
234         *p='\0';
235         value_expected=MagickFalse;
236         while ((isspace((int) ((unsigned char) c)) != 0) || (c == '='))
237         {
238           if (c == '=')
239             value_expected=MagickTrue;
240           c=ReadBlobByte(image);
241           count++;
242         }
243         if (value_expected == MagickFalse)
244           continue;
245         p=value;
246         while (isalnum((int) ((unsigned char) c)))
247         {
248           if ((size_t) (p-value) < (MagickPathExtent-1))
249             *p++=c;
250           c=ReadBlobByte(image);
251           count++;
252         }
253         *p='\0';
254         /*
255           Assign a value to the specified keyword.
256         */
257         if (LocaleCompare(keyword,"LABEL_RECORDS") == 0)
258           length*=(ssize_t) StringToLong(value);
259         if (LocaleCompare(keyword,"LBLSIZE") == 0)
260           length=(ssize_t) StringToLong(value);
261         if (LocaleCompare(keyword,"RECORD_BYTES") == 0)
262           {
263             image->columns=StringToUnsignedLong(value);
264             length=(ssize_t) image->columns;
265           }
266         if (LocaleCompare(keyword,"NS") == 0)
267           image->columns=StringToUnsignedLong(value);
268         if (LocaleCompare(keyword,"LINES") == 0)
269           image->rows=StringToUnsignedLong(value);
270         if (LocaleCompare(keyword,"NL") == 0)
271           image->rows=StringToUnsignedLong(value);
272       }
273     while (isspace((int) ((unsigned char) c)) != 0)
274     {
275       c=ReadBlobByte(image);
276       count++;
277     }
278   }
279   while (count < (ssize_t) length)
280   {
281     c=ReadBlobByte(image);
282     if (c == EOF)
283       break;
284     count++;
285   }
286   if ((image->columns == 0) || (image->rows == 0))
287     ThrowReaderException(CorruptImageError,"NegativeOrZeroImageSize");
288   image->depth=8;
289   if (image_info->ping != MagickFalse)
290     {
291       (void) CloseBlob(image);
292       return(GetFirstImageInList(image));
293     }
294   status=SetImageExtent(image,image->columns,image->rows,exception);
295   if (status == MagickFalse)
296     return(DestroyImageList(image));
297   /*
298     Read VICAR pixels.
299   */
300   (void) SetImageColorspace(image,GRAYColorspace,exception);
301   quantum_type=GrayQuantum;
302   quantum_info=AcquireQuantumInfo(image_info,image);
303   if (quantum_info == (QuantumInfo *) NULL)
304     ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
305   length=GetQuantumExtent(image,quantum_info,quantum_type);
306   pixels=GetQuantumPixels(quantum_info);
307   for (y=0; y < (ssize_t) image->rows; y++)
308   {
309     const void
310       *stream;
311 
312     q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);
313     if (q == (Quantum *) NULL)
314       break;
315     stream=ReadBlobStream(image,length,pixels,&count);
316     if (count != (ssize_t) length)
317       break;
318     (void) ImportQuantumPixels(image,(CacheView *) NULL,quantum_info,
319       quantum_type,(unsigned char *) stream,exception);
320     if (SyncAuthenticPixels(image,exception) == MagickFalse)
321       break;
322     status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y,
323       image->rows);
324     if (status == MagickFalse)
325       break;
326   }
327   SetQuantumImageType(image,quantum_type);
328   quantum_info=DestroyQuantumInfo(quantum_info);
329   if (EOFBlob(image) != MagickFalse)
330     ThrowFileException(exception,CorruptImageError,"UnexpectedEndOfFile",
331       image->filename);
332   (void) CloseBlob(image);
333   return(GetFirstImageInList(image));
334 }
335 
336 /*
337 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
338 %                                                                             %
339 %                                                                             %
340 %                                                                             %
341 %   R e g i s t e r V I C A R I m a g e                                       %
342 %                                                                             %
343 %                                                                             %
344 %                                                                             %
345 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
346 %
347 %  RegisterVICARImage() adds attributes for the VICAR image format to
348 %  the list of supported formats.  The attributes include the image format
349 %  tag, a method to read and/or write the format, whether the format
350 %  supports the saving of more than one frame to the same file or blob,
351 %  whether the format supports native in-memory I/O, and a brief
352 %  description of the format.
353 %
354 %  The format of the RegisterVICARImage method is:
355 %
356 %      size_t RegisterVICARImage(void)
357 %
358 */
RegisterVICARImage(void)359 ModuleExport size_t RegisterVICARImage(void)
360 {
361   MagickInfo
362     *entry;
363 
364   entry=AcquireMagickInfo("VICAR","VICAR","VICAR rasterfile format");
365   entry->decoder=(DecodeImageHandler *) ReadVICARImage;
366   entry->encoder=(EncodeImageHandler *) WriteVICARImage;
367   entry->magick=(IsImageFormatHandler *) IsVICAR;
368   entry->flags^=CoderAdjoinFlag;
369   (void) RegisterMagickInfo(entry);
370   return(MagickImageCoderSignature);
371 }
372 
373 /*
374 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
375 %                                                                             %
376 %                                                                             %
377 %                                                                             %
378 %   U n r e g i s t e r V I C A R I m a g e                                   %
379 %                                                                             %
380 %                                                                             %
381 %                                                                             %
382 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
383 %
384 %  UnregisterVICARImage() removes format registrations made by the
385 %  VICAR module from the list of supported formats.
386 %
387 %  The format of the UnregisterVICARImage method is:
388 %
389 %      UnregisterVICARImage(void)
390 %
391 */
UnregisterVICARImage(void)392 ModuleExport void UnregisterVICARImage(void)
393 {
394   (void) UnregisterMagickInfo("VICAR");
395 }
396 
397 /*
398 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
399 %                                                                             %
400 %                                                                             %
401 %                                                                             %
402 %   W r i t e V I C A R I m a g e                                             %
403 %                                                                             %
404 %                                                                             %
405 %                                                                             %
406 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
407 %
408 %  WriteVICARImage() writes an image in the VICAR rasterfile format.
409 %  Vicar files contain a text header, followed by one or more planes of binary
410 %  grayscale image data.  Vicar files are designed to allow many planes to be
411 %  stacked together to form image cubes.  This method only writes a single
412 %  grayscale plane.
413 %
414 %  WriteVICARImage was written contributed by gorelick@esther.la.asu.edu.
415 %
416 %  The format of the WriteVICARImage method is:
417 %
418 %      MagickBooleanType WriteVICARImage(const ImageInfo *image_info,
419 %        Image *image,ExceptionInfo *exception)
420 %
421 %  A description of each parameter follows.
422 %
423 %    o image_info: the image info.
424 %
425 %    o image:  The image.
426 %
427 %    o exception: return any errors or warnings in this structure.
428 %
429 */
WriteVICARImage(const ImageInfo * image_info,Image * image,ExceptionInfo * exception)430 static MagickBooleanType WriteVICARImage(const ImageInfo *image_info,
431   Image *image,ExceptionInfo *exception)
432 {
433   char
434     header[MagickPathExtent];
435 
436   int
437     y;
438 
439   MagickBooleanType
440     status;
441 
442   QuantumInfo
443     *quantum_info;
444 
445   const Quantum
446     *p;
447 
448   size_t
449     length;
450 
451   ssize_t
452     count;
453 
454   unsigned char
455     *pixels;
456 
457   /*
458     Open output image file.
459   */
460   assert(image_info != (const ImageInfo *) NULL);
461   assert(image_info->signature == MagickCoreSignature);
462   assert(image != (Image *) NULL);
463   assert(image->signature == MagickCoreSignature);
464   if (image->debug != MagickFalse)
465     (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
466   assert(exception != (ExceptionInfo *) NULL);
467   assert(exception->signature == MagickCoreSignature);
468   status=OpenBlob(image_info,image,WriteBinaryBlobMode,exception);
469   if (status == MagickFalse)
470     return(status);
471   (void) TransformImageColorspace(image,sRGBColorspace,exception);
472   /*
473     Write header.
474   */
475   (void) memset(header,' ',MagickPathExtent);
476   (void) FormatLocaleString(header,MagickPathExtent,
477     "LBLSIZE=%.20g FORMAT='BYTE' TYPE='IMAGE' BUFSIZE=20000 DIM=2 EOL=0 "
478     "RECSIZE=%.20g ORG='BSQ' NL=%.20g NS=%.20g NB=1 N1=0 N2=0 N3=0 N4=0 NBB=0 "
479     "NLB=0 TASK='ImageMagick'",(double) MagickPathExtent,(double) image->columns,
480     (double) image->rows,(double) image->columns);
481   (void) WriteBlob(image,MagickPathExtent,(unsigned char *) header);
482   /*
483     Write VICAR pixels.
484   */
485   image->depth=8;
486   quantum_info=AcquireQuantumInfo(image_info,image);
487   if (quantum_info == (QuantumInfo *) NULL)
488     ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed");
489   pixels=(unsigned char *) GetQuantumPixels(quantum_info);
490   for (y=0; y < (ssize_t) image->rows; y++)
491   {
492     p=GetVirtualPixels(image,0,y,image->columns,1,exception);
493     if (p == (const Quantum *) NULL)
494       break;
495     length=ExportQuantumPixels(image,(CacheView *) NULL,quantum_info,
496       GrayQuantum,pixels,exception);
497     count=WriteBlob(image,length,pixels);
498     if (count != (ssize_t) length)
499       break;
500     status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y,
501       image->rows);
502     if (status == MagickFalse)
503       break;
504   }
505   quantum_info=DestroyQuantumInfo(quantum_info);
506   (void) CloseBlob(image);
507   return(MagickTrue);
508 }
509