]> granicus.if.org Git - imagemagick/blob - coders/sun.c
...
[imagemagick] / coders / sun.c
1 /*
2 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
3 %                                                                             %
4 %                                                                             %
5 %                                                                             %
6 %                            SSSSS  U   U  N   N                              %
7 %                            SS     U   U  NN  N                              %
8 %                             SSS   U   U  N N N                              %
9 %                               SS  U   U  N  NN                              %
10 %                            SSSSS   UUU   N   N                              %
11 %                                                                             %
12 %                                                                             %
13 %                    Read/Write Sun Rasterfile Image Format                   %
14 %                                                                             %
15 %                              Software Design                                %
16 %                                   Cristy                                    %
17 %                                 July 1992                                   %
18 %                                                                             %
19 %                                                                             %
20 %  Copyright 1999-2017 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://www.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 \f
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/color.h"
48 #include "MagickCore/color-private.h"
49 #include "MagickCore/colormap.h"
50 #include "MagickCore/colormap-private.h"
51 #include "MagickCore/colorspace.h"
52 #include "MagickCore/colorspace-private.h"
53 #include "MagickCore/exception.h"
54 #include "MagickCore/exception-private.h"
55 #include "MagickCore/image.h"
56 #include "MagickCore/image-private.h"
57 #include "MagickCore/list.h"
58 #include "MagickCore/magick.h"
59 #include "MagickCore/memory_.h"
60 #include "MagickCore/memory-private.h"
61 #include "MagickCore/monitor.h"
62 #include "MagickCore/monitor-private.h"
63 #include "MagickCore/pixel-accessor.h"
64 #include "MagickCore/quantum-private.h"
65 #include "MagickCore/static.h"
66 #include "MagickCore/string_.h"
67 #include "MagickCore/module.h"
68 \f
69 /*
70   Forward declarations.
71 */
72 static MagickBooleanType
73   WriteSUNImage(const ImageInfo *,Image *,ExceptionInfo *);
74 \f
75 /*
76 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
77 %                                                                             %
78 %                                                                             %
79 %                                                                             %
80 %   I s S U N                                                                 %
81 %                                                                             %
82 %                                                                             %
83 %                                                                             %
84 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
85 %
86 %  IsSUN() returns MagickTrue if the image format type, identified by the
87 %  magick string, is SUN.
88 %
89 %  The format of the IsSUN method is:
90 %
91 %      MagickBooleanType IsSUN(const unsigned char *magick,const size_t length)
92 %
93 %  A description of each parameter follows:
94 %
95 %    o magick: compare image format pattern against these bytes.
96 %
97 %    o length: Specifies the length of the magick string.
98 %
99 */
100 static MagickBooleanType IsSUN(const unsigned char *magick,const size_t length)
101 {
102   if (length < 4)
103     return(MagickFalse);
104   if (memcmp(magick,"\131\246\152\225",4) == 0)
105     return(MagickTrue);
106   return(MagickFalse);
107 }
108 \f
109 /*
110 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
111 %                                                                             %
112 %                                                                             %
113 %                                                                             %
114 %   D e c o d e I m a g e                                                     %
115 %                                                                             %
116 %                                                                             %
117 %                                                                             %
118 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
119 %
120 %  DecodeImage unpacks the packed image pixels into  runlength-encoded pixel
121 %  packets.
122 %
123 %  The format of the DecodeImage method is:
124 %
125 %      MagickBooleanType DecodeImage(const unsigned char *compressed_pixels,
126 %        const size_t length,unsigned char *pixels)
127 %
128 %  A description of each parameter follows:
129 %
130 %    o compressed_pixels:  The address of a byte (8 bits) array of compressed
131 %      pixel data.
132 %
133 %    o length:  An integer value that is the total number of bytes of the
134 %      source image (as just read by ReadBlob)
135 %
136 %    o pixels:  The address of a byte (8 bits) array of pixel data created by
137 %      the uncompression process.  The number of bytes in this array
138 %      must be at least equal to the number columns times the number of rows
139 %      of the source pixels.
140 %
141 */
142 static MagickBooleanType DecodeImage(const unsigned char *compressed_pixels,
143   const size_t length,unsigned char *pixels,size_t extent)
144 {
145   register const unsigned char
146     *p;
147
148   register unsigned char
149     *q;
150
151   ssize_t
152     count;
153
154   unsigned char
155     byte;
156
157   (void) LogMagickEvent(TraceEvent,GetMagickModule(),"...");
158   assert(compressed_pixels != (unsigned char *) NULL);
159   assert(pixels != (unsigned char *) NULL);
160   p=compressed_pixels;
161   q=pixels;
162   while (((size_t) (p-compressed_pixels) < length) &&
163          ((size_t) (q-pixels) < extent))
164   {
165     byte=(*p++);
166     if (byte != 128U)
167       *q++=byte;
168     else
169       {
170         /*
171           Runlength-encoded packet: <count><byte>.
172         */
173         if (((size_t) (p-compressed_pixels) >= length))
174           break;
175         count=(*p++);
176         if (count > 0)
177           {
178             if (((size_t) (p-compressed_pixels) >= length))
179               break;
180             byte=(*p++);
181           }
182         while ((count >= 0) && ((size_t) (q-pixels) < extent))
183         {
184           *q++=byte;
185           count--;
186         }
187      }
188   }
189   return(((size_t) (q-pixels) == extent) ? MagickTrue : MagickFalse);
190 }
191 \f
192 /*
193 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
194 %                                                                             %
195 %                                                                             %
196 %                                                                             %
197 %   R e a d S U N I m a g e                                                   %
198 %                                                                             %
199 %                                                                             %
200 %                                                                             %
201 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
202 %
203 %  ReadSUNImage() reads a SUN image file and returns it.  It allocates
204 %  the memory necessary for the new Image structure and returns a pointer to
205 %  the new image.
206 %
207 %  The format of the ReadSUNImage method is:
208 %
209 %      Image *ReadSUNImage(const ImageInfo *image_info,ExceptionInfo *exception)
210 %
211 %  A description of each parameter follows:
212 %
213 %    o image_info: the image info.
214 %
215 %    o exception: return any errors or warnings in this structure.
216 %
217 */
218 static Image *ReadSUNImage(const ImageInfo *image_info,ExceptionInfo *exception)
219 {
220 #define RMT_EQUAL_RGB  1
221 #define RMT_NONE  0
222 #define RMT_RAW  2
223 #define RT_STANDARD  1
224 #define RT_ENCODED  2
225 #define RT_FORMAT_RGB  3
226
227   typedef struct _SUNInfo
228   {
229     unsigned int
230       magic,
231       width,
232       height,
233       depth,
234       length,
235       type,
236       maptype,
237       maplength;
238   } SUNInfo;
239
240   Image
241     *image;
242
243   int
244     bit;
245
246   MagickBooleanType
247     status;
248
249   MagickSizeType
250     number_pixels;
251
252   register Quantum
253     *q;
254
255   register ssize_t
256     i,
257     x;
258
259   register unsigned char
260     *p;
261
262   size_t
263     bytes_per_line,
264     extent,
265     height,
266     pixels_length,
267     quantum;
268
269   ssize_t
270     count,
271     y;
272
273   SUNInfo
274     sun_info;
275
276   unsigned char
277     *sun_data,
278     *sun_pixels;
279
280   /*
281     Open image file.
282   */
283   assert(image_info != (const ImageInfo *) NULL);
284   assert(image_info->signature == MagickCoreSignature);
285   if (image_info->debug != MagickFalse)
286     (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",
287       image_info->filename);
288   assert(exception != (ExceptionInfo *) NULL);
289   assert(exception->signature == MagickCoreSignature);
290   image=AcquireImage(image_info,exception);
291   status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception);
292   if (status == MagickFalse)
293     {
294       image=DestroyImageList(image);
295       return((Image *) NULL);
296     }
297   /*
298     Read SUN raster header.
299   */
300   (void) ResetMagickMemory(&sun_info,0,sizeof(sun_info));
301   sun_info.magic=ReadBlobMSBLong(image);
302   do
303   {
304     /*
305       Verify SUN identifier.
306     */
307     if (sun_info.magic != 0x59a66a95)
308       ThrowReaderException(CorruptImageError,"ImproperImageHeader");
309     sun_info.width=ReadBlobMSBLong(image);
310     sun_info.height=ReadBlobMSBLong(image);
311     sun_info.depth=ReadBlobMSBLong(image);
312     sun_info.length=ReadBlobMSBLong(image);
313     sun_info.type=ReadBlobMSBLong(image);
314     sun_info.maptype=ReadBlobMSBLong(image);
315     sun_info.maplength=ReadBlobMSBLong(image);
316     extent=sun_info.height*sun_info.width;
317     if ((sun_info.height != 0) && (sun_info.width != extent/sun_info.height))
318       ThrowReaderException(CorruptImageError,"ImproperImageHeader");
319     if ((sun_info.type != RT_STANDARD) && (sun_info.type != RT_ENCODED) &&
320         (sun_info.type != RT_FORMAT_RGB))
321       ThrowReaderException(CorruptImageError,"ImproperImageHeader");
322     if ((sun_info.maptype == RMT_NONE) && (sun_info.maplength != 0))
323       ThrowReaderException(CorruptImageError,"ImproperImageHeader");
324     if ((sun_info.depth != 1) && (sun_info.depth != 8) &&
325         (sun_info.depth != 24) && (sun_info.depth != 32))
326       ThrowReaderException(CorruptImageError,"ImproperImageHeader");
327     if ((sun_info.maptype != RMT_NONE) && (sun_info.maptype != RMT_EQUAL_RGB) &&
328         (sun_info.maptype != RMT_RAW))
329       ThrowReaderException(CoderError,"ColormapTypeNotSupported");
330     image->columns=sun_info.width;
331     image->rows=sun_info.height;
332     image->depth=sun_info.depth <= 8 ? sun_info.depth :
333       MAGICKCORE_QUANTUM_DEPTH;
334     if (sun_info.depth < 24)
335       {
336         size_t
337           one;
338
339         image->colors=sun_info.maplength;
340         one=1;
341         if (sun_info.maptype == RMT_NONE)
342           image->colors=one << sun_info.depth;
343         if (sun_info.maptype == RMT_EQUAL_RGB)
344           image->colors=sun_info.maplength/3;
345         if (AcquireImageColormap(image,image->colors,exception) == MagickFalse)
346           ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
347       }
348     switch (sun_info.maptype)
349     {
350       case RMT_NONE:
351         break;
352       case RMT_EQUAL_RGB:
353       {
354         unsigned char
355           *sun_colormap;
356
357         /*
358           Read SUN raster colormap.
359         */
360         sun_colormap=(unsigned char *) AcquireQuantumMemory(image->colors,
361           sizeof(*sun_colormap));
362         if (sun_colormap == (unsigned char *) NULL)
363           ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
364         count=ReadBlob(image,image->colors,sun_colormap);
365         if (count != (ssize_t) image->colors)
366           {
367             sun_colormap=(unsigned char *) RelinquishMagickMemory(sun_colormap);
368             ThrowReaderException(CorruptImageError,"UnexpectedEndOfFile");
369           }
370         for (i=0; i < (ssize_t) image->colors; i++)
371           image->colormap[i].red=(MagickRealType) ScaleCharToQuantum(
372             sun_colormap[i]);
373         count=ReadBlob(image,image->colors,sun_colormap);
374         if (count != (ssize_t) image->colors)
375           {
376             sun_colormap=(unsigned char *) RelinquishMagickMemory(sun_colormap);
377             ThrowReaderException(CorruptImageError,"UnexpectedEndOfFile");
378           }
379         for (i=0; i < (ssize_t) image->colors; i++)
380           image->colormap[i].green=(MagickRealType) ScaleCharToQuantum(
381             sun_colormap[i]);
382         count=ReadBlob(image,image->colors,sun_colormap);
383         if (count != (ssize_t) image->colors)
384           {
385             sun_colormap=(unsigned char *) RelinquishMagickMemory(sun_colormap);
386             ThrowReaderException(CorruptImageError,"UnexpectedEndOfFile");
387           }
388         for (i=0; i < (ssize_t) image->colors; i++)
389           image->colormap[i].blue=(MagickRealType) ScaleCharToQuantum(
390             sun_colormap[i]);
391         sun_colormap=(unsigned char *) RelinquishMagickMemory(sun_colormap);
392         break;
393       }
394       case RMT_RAW:
395       {
396         unsigned char
397           *sun_colormap;
398
399         /*
400           Read SUN raster colormap.
401         */
402         sun_colormap=(unsigned char *) AcquireQuantumMemory(sun_info.maplength,
403           sizeof(*sun_colormap));
404         if (sun_colormap == (unsigned char *) NULL)
405           ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
406         count=ReadBlob(image,sun_info.maplength,sun_colormap);
407         sun_colormap=(unsigned char *) RelinquishMagickMemory(sun_colormap);
408         if (count != (ssize_t) sun_info.maplength)
409           ThrowReaderException(CorruptImageError,"UnexpectedEndOfFile");
410         break;
411       }
412       default:
413         ThrowReaderException(CoderError,"ColormapTypeNotSupported");
414     }
415     image->alpha_trait=sun_info.depth == 32 ? BlendPixelTrait :
416       UndefinedPixelTrait;
417     image->columns=sun_info.width;
418     image->rows=sun_info.height;
419     if (image_info->ping != MagickFalse)
420       {
421         (void) CloseBlob(image);
422         return(GetFirstImageInList(image));
423       }
424     status=SetImageExtent(image,image->columns,image->rows,exception);
425     if (status == MagickFalse)
426       return(DestroyImageList(image));
427     if (sun_info.length == 0)
428       ThrowReaderException(ResourceLimitError,"ImproperImageHeader");
429     number_pixels=(MagickSizeType) (image->columns*image->rows);
430     if ((sun_info.type != RT_ENCODED) &&
431         ((number_pixels*sun_info.depth) > (8UL*sun_info.length)))
432       ThrowReaderException(CorruptImageError,"ImproperImageHeader");
433     if (HeapOverflowSanityCheck(sun_info.width,sun_info.depth) != MagickFalse)
434       ThrowReaderException(CorruptImageError,"ImproperImageHeader");
435     bytes_per_line=sun_info.width*sun_info.depth;
436     sun_data=(unsigned char *) AcquireQuantumMemory(sun_info.length,
437       sizeof(*sun_data));
438     if (sun_data == (unsigned char *) NULL)
439       ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
440     count=(ssize_t) ReadBlob(image,sun_info.length,sun_data);
441     if (count != (ssize_t) sun_info.length)
442       {
443         sun_data=(unsigned char *) RelinquishMagickMemory(sun_data);
444         ThrowReaderException(CorruptImageError,"UnableToReadImageData");
445       }
446     height=sun_info.height;
447     if ((height == 0) || (sun_info.width == 0) || (sun_info.depth == 0) ||
448         ((bytes_per_line/sun_info.depth) != sun_info.width))
449       {
450         sun_data=(unsigned char *) RelinquishMagickMemory(sun_data);
451         ThrowReaderException(ResourceLimitError,"ImproperImageHeader");
452       }
453     quantum=sun_info.depth == 1 ? 15 : 7;
454     bytes_per_line+=quantum;
455     bytes_per_line<<=1;
456     if ((bytes_per_line >> 1) != (sun_info.width*sun_info.depth+quantum))
457       {
458         sun_data=(unsigned char *) RelinquishMagickMemory(sun_data);
459         ThrowReaderException(ResourceLimitError,"ImproperImageHeader");
460       }
461     bytes_per_line>>=4;
462     if (HeapOverflowSanityCheck(height,bytes_per_line) != MagickFalse)
463       {
464         sun_data=(unsigned char *) RelinquishMagickMemory(sun_data);
465         ThrowReaderException(ResourceLimitError,"ImproperImageHeader");
466       }
467     pixels_length=height*bytes_per_line;
468     sun_pixels=(unsigned char *) AcquireQuantumMemory(pixels_length+image->rows,
469       sizeof(*sun_pixels));
470     if (sun_pixels == (unsigned char *) NULL)
471       {
472         sun_data=(unsigned char *) RelinquishMagickMemory(sun_data);
473         ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
474       }
475     ResetMagickMemory(sun_pixels,0,pixels_length*sizeof(*sun_pixels));
476     if (sun_info.type == RT_ENCODED)
477       {
478         status=DecodeImage(sun_data,sun_info.length,sun_pixels,pixels_length);
479         if (status == MagickFalse)
480           ThrowReaderException(CorruptImageError,"UnableToReadImageData");
481       }
482     else
483       {
484         if (sun_info.length > pixels_length)
485           {
486             sun_data=(unsigned char *) RelinquishMagickMemory(sun_data);
487             sun_pixels=(unsigned char *) RelinquishMagickMemory(sun_pixels);
488             ThrowReaderException(ResourceLimitError,"ImproperImageHeader");
489           }
490         (void) CopyMagickMemory(sun_pixels,sun_data,sun_info.length);
491       }
492     sun_data=(unsigned char *) RelinquishMagickMemory(sun_data);
493     /*
494       Convert SUN raster image to pixel packets.
495     */
496     p=sun_pixels;
497     if (sun_info.depth == 1)
498       for (y=0; y < (ssize_t) image->rows; y++)
499       {
500         q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);
501         if (q == (Quantum *) NULL)
502           break;
503         for (x=0; x < ((ssize_t) image->columns-7); x+=8)
504         {
505           for (bit=7; bit >= 0; bit--)
506           {
507             SetPixelIndex(image,(Quantum) ((*p) & (0x01 << bit) ? 0x00 : 0x01),
508               q);
509             q+=GetPixelChannels(image);
510           }
511           p++;
512         }
513         if ((image->columns % 8) != 0)
514           {
515             for (bit=7; bit >= (int) (8-(image->columns % 8)); bit--)
516             {
517               SetPixelIndex(image,(Quantum) ((*p) & (0x01 << bit) ? 0x00 :
518                 0x01),q);
519               q+=GetPixelChannels(image);
520             }
521             p++;
522           }
523         if ((((image->columns/8)+(image->columns % 8 ? 1 : 0)) % 2) != 0)
524           p++;
525         if (SyncAuthenticPixels(image,exception) == MagickFalse)
526           break;
527         if (image->previous == (Image *) NULL)
528           {
529             status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y,
530               image->rows);
531             if (status == MagickFalse)
532               break;
533           }
534       }
535     else
536       if (image->storage_class == PseudoClass)
537         {
538           for (y=0; y < (ssize_t) image->rows; y++)
539           {
540             q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);
541             if (q == (Quantum *) NULL)
542               break;
543             for (x=0; x < (ssize_t) image->columns; x++)
544             {
545               SetPixelIndex(image,ConstrainColormapIndex(image,*p,exception),q);
546               p++;
547               q+=GetPixelChannels(image);
548             }
549             if ((image->columns % 2) != 0)
550               p++;
551             if (SyncAuthenticPixels(image,exception) == MagickFalse)
552               break;
553             if (image->previous == (Image *) NULL)
554               {
555                 status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y,
556                 image->rows);
557                 if (status == MagickFalse)
558                   break;
559               }
560           }
561         }
562       else
563         {
564           size_t
565             bytes_per_pixel;
566
567           bytes_per_pixel=3;
568           if (image->alpha_trait != UndefinedPixelTrait)
569             bytes_per_pixel++;
570           if (bytes_per_line == 0)
571             bytes_per_line=bytes_per_pixel*image->columns;
572           for (y=0; y < (ssize_t) image->rows; y++)
573           {
574             q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);
575             if (q == (Quantum *) NULL)
576               break;
577             for (x=0; x < (ssize_t) image->columns; x++)
578             {
579               if (image->alpha_trait != UndefinedPixelTrait)
580                 SetPixelAlpha(image,ScaleCharToQuantum(*p++),q);
581               if (sun_info.type == RT_STANDARD)
582                 {
583                   SetPixelBlue(image,ScaleCharToQuantum(*p++),q);
584                   SetPixelGreen(image,ScaleCharToQuantum(*p++),q);
585                   SetPixelRed(image,ScaleCharToQuantum(*p++),q);
586                 }
587               else
588                 {
589                   SetPixelRed(image,ScaleCharToQuantum(*p++),q);
590                   SetPixelGreen(image,ScaleCharToQuantum(*p++),q);
591                   SetPixelBlue(image,ScaleCharToQuantum(*p++),q);
592                 }
593               if (image->colors != 0)
594                 {
595                   SetPixelRed(image,ClampToQuantum(image->colormap[(ssize_t)
596                     GetPixelRed(image,q)].red),q);
597                   SetPixelGreen(image,ClampToQuantum(image->colormap[(ssize_t)
598                     GetPixelGreen(image,q)].green),q);
599                   SetPixelBlue(image,ClampToQuantum(image->colormap[(ssize_t)
600                     GetPixelBlue(image,q)].blue),q);
601                 }
602               q+=GetPixelChannels(image);
603             }
604             if (((bytes_per_pixel*image->columns) % 2) != 0)
605               p++;
606             if (SyncAuthenticPixels(image,exception) == MagickFalse)
607               break;
608             if (image->previous == (Image *) NULL)
609               {
610                 status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y,
611                 image->rows);
612                 if (status == MagickFalse)
613                   break;
614               }
615           }
616         }
617     if (image->storage_class == PseudoClass)
618       (void) SyncImage(image,exception);
619     sun_pixels=(unsigned char *) RelinquishMagickMemory(sun_pixels);
620     if (EOFBlob(image) != MagickFalse)
621       {
622         ThrowFileException(exception,CorruptImageError,"UnexpectedEndOfFile",
623           image->filename);
624         break;
625       }
626     /*
627       Proceed to next image.
628     */
629     if (image_info->number_scenes != 0)
630       if (image->scene >= (image_info->scene+image_info->number_scenes-1))
631         break;
632     sun_info.magic=ReadBlobMSBLong(image);
633     if (sun_info.magic == 0x59a66a95)
634       {
635         /*
636           Allocate next image structure.
637         */
638         AcquireNextImage(image_info,image,exception);
639         if (GetNextImageInList(image) == (Image *) NULL)
640           {
641             image=DestroyImageList(image);
642             return((Image *) NULL);
643           }
644         image=SyncNextImageInList(image);
645         status=SetImageProgress(image,LoadImagesTag,TellBlob(image),
646           GetBlobSize(image));
647         if (status == MagickFalse)
648           break;
649       }
650   } while (sun_info.magic == 0x59a66a95);
651   (void) CloseBlob(image);
652   return(GetFirstImageInList(image));
653 }
654 \f
655 /*
656 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
657 %                                                                             %
658 %                                                                             %
659 %                                                                             %
660 %   R e g i s t e r S U N I m a g e                                           %
661 %                                                                             %
662 %                                                                             %
663 %                                                                             %
664 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
665 %
666 %  RegisterSUNImage() adds attributes for the SUN image format to
667 %  the list of supported formats.  The attributes include the image format
668 %  tag, a method to read and/or write the format, whether the format
669 %  supports the saving of more than one frame to the same file or blob,
670 %  whether the format supports native in-memory I/O, and a brief
671 %  description of the format.
672 %
673 %  The format of the RegisterSUNImage method is:
674 %
675 %      size_t RegisterSUNImage(void)
676 %
677 */
678 ModuleExport size_t RegisterSUNImage(void)
679 {
680   MagickInfo
681     *entry;
682
683   entry=AcquireMagickInfo("SUN","RAS","SUN Rasterfile");
684   entry->decoder=(DecodeImageHandler *) ReadSUNImage;
685   entry->encoder=(EncodeImageHandler *) WriteSUNImage;
686   entry->magick=(IsImageFormatHandler *) IsSUN;
687   (void) RegisterMagickInfo(entry);
688   entry=AcquireMagickInfo("SUN","SUN","SUN Rasterfile");
689   entry->decoder=(DecodeImageHandler *) ReadSUNImage;
690   entry->encoder=(EncodeImageHandler *) WriteSUNImage;
691   (void) RegisterMagickInfo(entry);
692   return(MagickImageCoderSignature);
693 }
694 \f
695 /*
696 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
697 %                                                                             %
698 %                                                                             %
699 %                                                                             %
700 %   U n r e g i s t e r S U N I m a g e                                       %
701 %                                                                             %
702 %                                                                             %
703 %                                                                             %
704 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
705 %
706 %  UnregisterSUNImage() removes format registrations made by the
707 %  SUN module from the list of supported formats.
708 %
709 %  The format of the UnregisterSUNImage method is:
710 %
711 %      UnregisterSUNImage(void)
712 %
713 */
714 ModuleExport void UnregisterSUNImage(void)
715 {
716   (void) UnregisterMagickInfo("RAS");
717   (void) UnregisterMagickInfo("SUN");
718 }
719 \f
720 /*
721 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
722 %                                                                             %
723 %                                                                             %
724 %                                                                             %
725 %   W r i t e S U N I m a g e                                                 %
726 %                                                                             %
727 %                                                                             %
728 %                                                                             %
729 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
730 %
731 %  WriteSUNImage() writes an image in the SUN rasterfile format.
732 %
733 %  The format of the WriteSUNImage method is:
734 %
735 %      MagickBooleanType WriteSUNImage(const ImageInfo *image_info,
736 %        Image *image,ExceptionInfo *exception)
737 %
738 %  A description of each parameter follows.
739 %
740 %    o image_info: the image info.
741 %
742 %    o image:  The image.
743 %
744 %    o exception: return any errors or warnings in this structure.
745 %
746 */
747 static MagickBooleanType WriteSUNImage(const ImageInfo *image_info,Image *image,
748   ExceptionInfo *exception)
749 {
750 #define RMT_EQUAL_RGB  1
751 #define RMT_NONE  0
752 #define RMT_RAW  2
753 #define RT_STANDARD  1
754 #define RT_FORMAT_RGB  3
755
756   typedef struct _SUNInfo
757   {
758     unsigned int
759       magic,
760       width,
761       height,
762       depth,
763       length,
764       type,
765       maptype,
766       maplength;
767   } SUNInfo;
768
769   MagickBooleanType
770     status;
771
772   MagickOffsetType
773     scene;
774
775   MagickSizeType
776     number_pixels;
777
778   register const Quantum
779     *p;
780
781   register ssize_t
782     i,
783     x;
784
785   ssize_t
786     y;
787
788   SUNInfo
789     sun_info;
790
791   /*
792     Open output image file.
793   */
794   assert(image_info != (const ImageInfo *) NULL);
795   assert(image_info->signature == MagickCoreSignature);
796   assert(image != (Image *) NULL);
797   assert(image->signature == MagickCoreSignature);
798   if (image->debug != MagickFalse)
799     (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
800   assert(exception != (ExceptionInfo *) NULL);
801   assert(exception->signature == MagickCoreSignature);
802   status=OpenBlob(image_info,image,WriteBinaryBlobMode,exception);
803   if (status == MagickFalse)
804     return(status);
805   scene=0;
806   do
807   {
808     /*
809       Initialize SUN raster file header.
810     */
811     (void) TransformImageColorspace(image,sRGBColorspace,exception);
812     sun_info.magic=0x59a66a95;
813     if ((image->columns != (unsigned int) image->columns) ||
814         (image->rows != (unsigned int) image->rows))
815       ThrowWriterException(ImageError,"WidthOrHeightExceedsLimit");
816     sun_info.width=(unsigned int) image->columns;
817     sun_info.height=(unsigned int) image->rows;
818     sun_info.type=(unsigned int)
819       (image->storage_class == DirectClass ? RT_FORMAT_RGB : RT_STANDARD);
820     sun_info.maptype=RMT_NONE;
821     sun_info.maplength=0;
822     number_pixels=(MagickSizeType) image->columns*image->rows;
823     if ((4*number_pixels) != (size_t) (4*number_pixels))
824       ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed");
825     if (image->storage_class == DirectClass)
826       {
827         /*
828           Full color SUN raster.
829         */
830         sun_info.depth=(unsigned int) image->alpha_trait !=
831           UndefinedPixelTrait ? 32U : 24U;
832         sun_info.length=(unsigned int) ((image->alpha_trait !=
833           UndefinedPixelTrait ? 4 : 3)*number_pixels);
834         sun_info.length+=sun_info.length & 0x01 ? (unsigned int) image->rows :
835           0;
836       }
837     else
838       if (SetImageMonochrome(image,exception) != MagickFalse)
839         {
840           /*
841             Monochrome SUN raster.
842           */
843           sun_info.depth=1;
844           sun_info.length=(unsigned int) (((image->columns+7) >> 3)*
845             image->rows);
846           sun_info.length+=(unsigned int) (((image->columns/8)+(image->columns %
847             8 ? 1 : 0)) % 2 ? image->rows : 0);
848         }
849       else
850         {
851           /*
852             Colormapped SUN raster.
853           */
854           sun_info.depth=8;
855           sun_info.length=(unsigned int) number_pixels;
856           sun_info.length+=(unsigned int) (image->columns & 0x01 ? image->rows :
857             0);
858           sun_info.maptype=RMT_EQUAL_RGB;
859           sun_info.maplength=(unsigned int) (3*image->colors);
860         }
861     /*
862       Write SUN header.
863     */
864     (void) WriteBlobMSBLong(image,sun_info.magic);
865     (void) WriteBlobMSBLong(image,sun_info.width);
866     (void) WriteBlobMSBLong(image,sun_info.height);
867     (void) WriteBlobMSBLong(image,sun_info.depth);
868     (void) WriteBlobMSBLong(image,sun_info.length);
869     (void) WriteBlobMSBLong(image,sun_info.type);
870     (void) WriteBlobMSBLong(image,sun_info.maptype);
871     (void) WriteBlobMSBLong(image,sun_info.maplength);
872     /*
873       Convert MIFF to SUN raster pixels.
874     */
875     x=0;
876     y=0;
877     if (image->storage_class == DirectClass)
878       {
879         register unsigned char
880           *q;
881
882         size_t
883           bytes_per_pixel,
884           length;
885
886         unsigned char
887           *pixels;
888
889         /*
890           Allocate memory for pixels.
891         */
892         bytes_per_pixel=3;
893         if (image->alpha_trait != UndefinedPixelTrait)
894           bytes_per_pixel++;
895         length=image->columns;
896         pixels=(unsigned char *) AcquireQuantumMemory(length,4*sizeof(*pixels));
897         if (pixels == (unsigned char *) NULL)
898           ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed");
899         /*
900           Convert DirectClass packet to SUN RGB pixel.
901         */
902         for (y=0; y < (ssize_t) image->rows; y++)
903         {
904           p=GetVirtualPixels(image,0,y,image->columns,1,exception);
905           if (p == (const Quantum *) NULL)
906             break;
907           q=pixels;
908           for (x=0; x < (ssize_t) image->columns; x++)
909           {
910             if (image->alpha_trait != UndefinedPixelTrait)
911               *q++=ScaleQuantumToChar(GetPixelAlpha(image,p));
912             *q++=ScaleQuantumToChar(GetPixelRed(image,p));
913             *q++=ScaleQuantumToChar(GetPixelGreen(image,p));
914             *q++=ScaleQuantumToChar(GetPixelBlue(image,p));
915             p+=GetPixelChannels(image);
916           }
917           if (((bytes_per_pixel*image->columns) & 0x01) != 0)
918             *q++='\0';  /* pad scanline */
919           (void) WriteBlob(image,(size_t) (q-pixels),pixels);
920           if (image->previous == (Image *) NULL)
921             {
922               status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y,
923                 image->rows);
924               if (status == MagickFalse)
925                 break;
926             }
927         }
928         pixels=(unsigned char *) RelinquishMagickMemory(pixels);
929       }
930     else
931       if (SetImageMonochrome(image,exception) != MagickFalse)
932         {
933           register unsigned char
934             bit,
935             byte;
936
937           /*
938             Convert PseudoClass image to a SUN monochrome image.
939           */
940           (void) SetImageType(image,BilevelType,exception);
941           for (y=0; y < (ssize_t) image->rows; y++)
942           {
943             p=GetVirtualPixels(image,0,y,image->columns,1,exception);
944             if (p == (const Quantum *) NULL)
945               break;
946             bit=0;
947             byte=0;
948             for (x=0; x < (ssize_t) image->columns; x++)
949             {
950               byte<<=1;
951               if (GetPixelLuma(image,p) < (QuantumRange/2.0))
952                 byte|=0x01;
953               bit++;
954               if (bit == 8)
955                 {
956                   (void) WriteBlobByte(image,byte);
957                   bit=0;
958                   byte=0;
959                 }
960               p+=GetPixelChannels(image);
961             }
962             if (bit != 0)
963               (void) WriteBlobByte(image,(unsigned char) (byte << (8-bit)));
964             if ((((image->columns/8)+
965                 (image->columns % 8 ? 1 : 0)) % 2) != 0)
966               (void) WriteBlobByte(image,0);  /* pad scanline */
967             if (image->previous == (Image *) NULL)
968               {
969                 status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y,
970                 image->rows);
971                 if (status == MagickFalse)
972                   break;
973               }
974           }
975         }
976       else
977         {
978           /*
979             Dump colormap to file.
980           */
981           for (i=0; i < (ssize_t) image->colors; i++)
982             (void) WriteBlobByte(image,ScaleQuantumToChar(
983               ClampToQuantum(image->colormap[i].red)));
984           for (i=0; i < (ssize_t) image->colors; i++)
985             (void) WriteBlobByte(image,ScaleQuantumToChar(
986               ClampToQuantum(image->colormap[i].green)));
987           for (i=0; i < (ssize_t) image->colors; i++)
988             (void) WriteBlobByte(image,ScaleQuantumToChar(
989               ClampToQuantum(image->colormap[i].blue)));
990           /*
991             Convert PseudoClass packet to SUN colormapped pixel.
992           */
993           for (y=0; y < (ssize_t) image->rows; y++)
994           {
995             p=GetVirtualPixels(image,0,y,image->columns,1,exception);
996             if (p == (const Quantum *) NULL)
997               break;
998             for (x=0; x < (ssize_t) image->columns; x++)
999             {
1000               (void) WriteBlobByte(image,(unsigned char)
1001                 GetPixelIndex(image,p));
1002               p+=GetPixelChannels(image);
1003             }
1004             if (image->columns & 0x01)
1005               (void) WriteBlobByte(image,0);  /* pad scanline */
1006             if (image->previous == (Image *) NULL)
1007               {
1008                 status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y,
1009                   image->rows);
1010                 if (status == MagickFalse)
1011                   break;
1012               }
1013           }
1014         }
1015     if (GetNextImageInList(image) == (Image *) NULL)
1016       break;
1017     image=SyncNextImageInList(image);
1018     status=SetImageProgress(image,SaveImagesTag,scene++,
1019       GetImageListLength(image));
1020     if (status == MagickFalse)
1021       break;
1022   } while (image_info->adjoin != MagickFalse);
1023   (void) CloseBlob(image);
1024   return(MagickTrue);
1025 }