]> granicus.if.org Git - imagemagick/blob - coders/pcx.c
Replaced CoderSeekableStreamFlag with CoderDecoderSeekableStreamFlag and CoderEncoder...
[imagemagick] / coders / pcx.c
1 /*
2 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
3 %                                                                             %
4 %                                                                             %
5 %                                                                             %
6 %                            PPPP    CCCC  X   X                              %
7 %                            P   P  C       X X                               %
8 %                            PPPP   C        X                                %
9 %                            P      C       X X                               %
10 %                            P       CCCC  X   X                              %
11 %                                                                             %
12 %                                                                             %
13 %                Read/Write ZSoft IBM PC Paintbrush 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 %    http://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/colorspace.h"
51 #include "MagickCore/colorspace-private.h"
52 #include "MagickCore/exception.h"
53 #include "MagickCore/exception-private.h"
54 #include "MagickCore/image.h"
55 #include "MagickCore/image-private.h"
56 #include "MagickCore/list.h"
57 #include "MagickCore/magick.h"
58 #include "MagickCore/memory_.h"
59 #include "MagickCore/memory-private.h"
60 #include "MagickCore/monitor.h"
61 #include "MagickCore/monitor-private.h"
62 #include "MagickCore/pixel-accessor.h"
63 #include "MagickCore/quantum-private.h"
64 #include "MagickCore/static.h"
65 #include "MagickCore/string_.h"
66 #include "MagickCore/module.h"
67 \f
68 /*
69   Typedef declarations.
70 */
71 typedef struct _PCXInfo
72 {
73   unsigned char
74     identifier,
75     version,
76     encoding,
77     bits_per_pixel;
78
79   unsigned short
80     left,
81     top,
82     right,
83     bottom,
84     horizontal_resolution,
85     vertical_resolution;
86
87   unsigned char
88     reserved,
89     planes;
90
91   unsigned short
92     bytes_per_line,
93     palette_info,
94     horizontal_screensize,
95     vertical_screensize;
96
97   unsigned char
98     colormap_signature;
99 } PCXInfo;
100 \f
101 /*
102   Forward declarations.
103 */
104 static MagickBooleanType
105   WritePCXImage(const ImageInfo *,Image *,ExceptionInfo *);
106 \f
107 /*
108 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
109 %                                                                             %
110 %                                                                             %
111 %                                                                             %
112 %   I s D C X                                                                 %
113 %                                                                             %
114 %                                                                             %
115 %                                                                             %
116 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
117 %
118 %  IsDCX() returns MagickTrue if the image format type, identified by the
119 %  magick string, is DCX.
120 %
121 %  The format of the IsDCX method is:
122 %
123 %      MagickBooleanType IsDCX(const unsigned char *magick,const size_t length)
124 %
125 %  A description of each parameter follows:
126 %
127 %    o magick: compare image format pattern against these bytes.
128 %
129 %    o length: Specifies the length of the magick string.
130 %
131 */
132 static MagickBooleanType IsDCX(const unsigned char *magick,const size_t length)
133 {
134   if (length < 4)
135     return(MagickFalse);
136   if (memcmp(magick,"\261\150\336\72",4) == 0)
137     return(MagickTrue);
138   return(MagickFalse);
139 }
140 \f
141 /*
142 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
143 %                                                                             %
144 %                                                                             %
145 %                                                                             %
146 %   I s P C X                                                                 %
147 %                                                                             %
148 %                                                                             %
149 %                                                                             %
150 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
151 %
152 %  IsPCX() returns MagickTrue if the image format type, identified by the
153 %  magick string, is PCX.
154 %
155 %  The format of the IsPCX method is:
156 %
157 %      MagickBooleanType IsPCX(const unsigned char *magick,const size_t length)
158 %
159 %  A description of each parameter follows:
160 %
161 %    o magick: compare image format pattern against these bytes.
162 %
163 %    o length: Specifies the length of the magick string.
164 %
165 */
166 static MagickBooleanType IsPCX(const unsigned char *magick,const size_t length)
167 {
168   if (length < 2)
169     return(MagickFalse);
170   if (memcmp(magick,"\012\002",2) == 0)
171     return(MagickTrue);
172   if (memcmp(magick,"\012\005",2) == 0)
173     return(MagickTrue);
174   return(MagickFalse);
175 }
176 \f
177 /*
178 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
179 %                                                                             %
180 %                                                                             %
181 %                                                                             %
182 %   R e a d P C X I m a g e                                                   %
183 %                                                                             %
184 %                                                                             %
185 %                                                                             %
186 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
187 %
188 %  ReadPCXImage() reads a ZSoft IBM PC Paintbrush file and returns it.
189 %  It allocates the memory necessary for the new Image structure and returns
190 %  a pointer to the new image.
191 %
192 %  The format of the ReadPCXImage method is:
193 %
194 %      Image *ReadPCXImage(const ImageInfo *image_info,ExceptionInfo *exception)
195 %
196 %  A description of each parameter follows:
197 %
198 %    o image_info: the image info.
199 %
200 %    o exception: return any errors or warnings in this structure.
201 %
202 */
203 static Image *ReadPCXImage(const ImageInfo *image_info,ExceptionInfo *exception)
204 {
205 #define ThrowPCXException(severity,tag) \
206   { \
207     scanline=(unsigned char *) RelinquishMagickMemory(scanline); \
208     pixel_info=RelinquishVirtualMemory(pixel_info); \
209     ThrowReaderException(severity,tag); \
210   }
211
212   Image
213     *image;
214
215   int
216     bits,
217     id,
218     mask;
219
220   MagickBooleanType
221     status;
222
223   MagickOffsetType
224     offset,
225     *page_table;
226
227   MemoryInfo
228     *pixel_info;
229
230   PCXInfo
231     pcx_info;
232
233   register ssize_t
234     x;
235
236   register Quantum
237     *q;
238
239   register ssize_t
240     i;
241
242   register unsigned char
243     *p,
244     *r;
245
246   size_t
247     one,
248     pcx_packets;
249
250   ssize_t
251     count,
252     y;
253
254   unsigned char
255     packet,
256     pcx_colormap[768],
257     *pixels,
258     *scanline;
259
260   /*
261     Open image file.
262   */
263   assert(image_info != (const ImageInfo *) NULL);
264   assert(image_info->signature == MagickCoreSignature);
265   if (image_info->debug != MagickFalse)
266     (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",
267       image_info->filename);
268   assert(exception != (ExceptionInfo *) NULL);
269   assert(exception->signature == MagickCoreSignature);
270   image=AcquireImage(image_info,exception);
271   status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception);
272   if (status == MagickFalse)
273     {
274       image=DestroyImageList(image);
275       return((Image *) NULL);
276     }
277   /*
278     Determine if this a PCX file.
279   */
280   page_table=(MagickOffsetType *) NULL;
281   if (LocaleCompare(image_info->magick,"DCX") == 0)
282     {
283       size_t
284         magic;
285
286       /*
287         Read the DCX page table.
288       */
289       magic=ReadBlobLSBLong(image);
290       if (magic != 987654321)
291         ThrowReaderException(CorruptImageError,"ImproperImageHeader");
292       page_table=(MagickOffsetType *) AcquireQuantumMemory(1024UL,
293         sizeof(*page_table));
294       if (page_table == (MagickOffsetType *) NULL)
295         ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
296       for (id=0; id < 1024; id++)
297       {
298         page_table[id]=(MagickOffsetType) ReadBlobLSBLong(image);
299         if (page_table[id] == 0)
300           break;
301       }
302     }
303   if (page_table != (MagickOffsetType *) NULL)
304     {
305       offset=SeekBlob(image,(MagickOffsetType) page_table[0],SEEK_SET);
306       if (offset < 0)
307         ThrowReaderException(CorruptImageError,"ImproperImageHeader");
308     }
309   count=ReadBlob(image,1,&pcx_info.identifier);
310   for (id=1; id < 1024; id++)
311   {
312     int
313       bits_per_pixel;
314
315     /*
316       Verify PCX identifier.
317     */
318     pcx_info.version=(unsigned char) ReadBlobByte(image);
319     if ((count != 1) || (pcx_info.identifier != 0x0a))
320       ThrowReaderException(CorruptImageError,"ImproperImageHeader");
321     pcx_info.encoding=(unsigned char) ReadBlobByte(image);
322     bits_per_pixel=ReadBlobByte(image);
323     if (bits_per_pixel == -1)
324       ThrowReaderException(CorruptImageError,"ImproperImageHeader");
325     pcx_info.bits_per_pixel=(unsigned char) bits_per_pixel;
326     pcx_info.left=ReadBlobLSBShort(image);
327     pcx_info.top=ReadBlobLSBShort(image);
328     pcx_info.right=ReadBlobLSBShort(image);
329     pcx_info.bottom=ReadBlobLSBShort(image);
330     pcx_info.horizontal_resolution=ReadBlobLSBShort(image);
331     pcx_info.vertical_resolution=ReadBlobLSBShort(image);
332     /*
333       Read PCX raster colormap.
334     */
335     image->columns=(size_t) MagickAbsoluteValue((ssize_t) pcx_info.right-
336       pcx_info.left)+1UL;
337     image->rows=(size_t) MagickAbsoluteValue((ssize_t) pcx_info.bottom-
338       pcx_info.top)+1UL;
339     if ((image->columns == 0) || (image->rows == 0) ||
340         ((pcx_info.bits_per_pixel != 1) &&
341          (pcx_info.bits_per_pixel != 2) &&
342          (pcx_info.bits_per_pixel != 4) &&
343          (pcx_info.bits_per_pixel != 8)))
344       ThrowReaderException(CorruptImageError,"ImproperImageHeader");
345     image->depth=pcx_info.bits_per_pixel;
346     image->units=PixelsPerInchResolution;
347     image->resolution.x=(double) pcx_info.horizontal_resolution;
348     image->resolution.y=(double) pcx_info.vertical_resolution;
349     image->colors=16;
350     count=ReadBlob(image,3*image->colors,pcx_colormap);
351     if (count != (ssize_t) (3*image->colors))
352       ThrowReaderException(CorruptImageError,"ImproperImageHeader");
353     pcx_info.reserved=(unsigned char) ReadBlobByte(image);
354     pcx_info.planes=(unsigned char) ReadBlobByte(image);
355     if ((pcx_info.bits_per_pixel*pcx_info.planes) >= 64)
356       ThrowReaderException(CorruptImageError,"ImproperImageHeader");
357     one=1;
358     if ((pcx_info.bits_per_pixel != 8) || (pcx_info.planes == 1))
359       if ((pcx_info.version == 3) || (pcx_info.version == 5) ||
360           ((pcx_info.bits_per_pixel*pcx_info.planes) == 1))
361         image->colors=(size_t) MagickMin(one << (1UL*
362           (pcx_info.bits_per_pixel*pcx_info.planes)),256UL);
363     if (AcquireImageColormap(image,image->colors,exception) == MagickFalse)
364       ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
365     if ((pcx_info.bits_per_pixel >= 8) && (pcx_info.planes != 1))
366       image->storage_class=DirectClass;
367     p=pcx_colormap;
368     for (i=0; i < (ssize_t) image->colors; i++)
369     {
370       image->colormap[i].red=ScaleCharToQuantum(*p++);
371       image->colormap[i].green=ScaleCharToQuantum(*p++);
372       image->colormap[i].blue=ScaleCharToQuantum(*p++);
373     }
374     pcx_info.bytes_per_line=ReadBlobLSBShort(image);
375     pcx_info.palette_info=ReadBlobLSBShort(image);
376     pcx_info.horizontal_screensize=ReadBlobLSBShort(image);
377     pcx_info.vertical_screensize=ReadBlobLSBShort(image);
378     for (i=0; i < 54; i++)
379       (void) ReadBlobByte(image);
380     if ((image_info->ping != MagickFalse) && (image_info->number_scenes != 0))
381       if (image->scene >= (image_info->scene+image_info->number_scenes-1))
382         break;
383     status=SetImageExtent(image,image->columns,image->rows,exception);
384     if (status == MagickFalse)
385       return(DestroyImageList(image));
386     /*
387       Read image data.
388     */
389     if (HeapOverflowSanityCheck(image->rows, (size_t) pcx_info.bytes_per_line) != MagickFalse)
390       ThrowReaderException(CorruptImageError,"ImproperImageHeader");
391     pcx_packets=(size_t) image->rows*pcx_info.bytes_per_line;
392     if (HeapOverflowSanityCheck(pcx_packets, (size_t)pcx_info.planes) != MagickFalse)
393       ThrowReaderException(CorruptImageError,"ImproperImageHeader");
394     pcx_packets=(size_t) pcx_packets*pcx_info.planes;
395     if ((size_t) (pcx_info.bits_per_pixel*pcx_info.planes*image->columns) >
396         (pcx_packets*8U))
397       ThrowReaderException(CorruptImageError,"ImproperImageHeader");
398     scanline=(unsigned char *) AcquireQuantumMemory(MagickMax(image->columns,
399       pcx_info.bytes_per_line),MagickMax(8,pcx_info.planes)*sizeof(*scanline));
400     pixel_info=AcquireVirtualMemory(pcx_packets,2*sizeof(*pixels));
401     if ((scanline == (unsigned char *) NULL) ||
402         (pixel_info == (MemoryInfo *) NULL))
403       {
404         if (scanline != (unsigned char *) NULL)
405           scanline=(unsigned char *) RelinquishMagickMemory(scanline);
406         if (pixel_info != (MemoryInfo *) NULL)
407           pixel_info=RelinquishVirtualMemory(pixel_info);
408         ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
409       }
410     pixels=(unsigned char *) GetVirtualMemoryBlob(pixel_info);
411     /*
412       Uncompress image data.
413     */
414     p=pixels;
415     if (pcx_info.encoding == 0)
416       while (pcx_packets != 0)
417       {
418         packet=(unsigned char) ReadBlobByte(image);
419         if (EOFBlob(image) != MagickFalse)
420           ThrowPCXException(CorruptImageError,"UnexpectedEndOfFile");
421         *p++=packet;
422         pcx_packets--;
423       }
424     else
425       while (pcx_packets != 0)
426       {
427         packet=(unsigned char) ReadBlobByte(image);
428         if (EOFBlob(image) != MagickFalse)
429           ThrowPCXException(CorruptImageError,"UnexpectedEndOfFile");
430         if ((packet & 0xc0) != 0xc0)
431           {
432             *p++=packet;
433             pcx_packets--;
434             continue;
435           }
436         count=(ssize_t) (packet & 0x3f);
437         packet=(unsigned char) ReadBlobByte(image);
438         if (EOFBlob(image) != MagickFalse)
439           ThrowPCXException(CorruptImageError,"UnexpectedEndOfFile");
440         for ( ; count != 0; count--)
441         {
442           *p++=packet;
443           pcx_packets--;
444           if (pcx_packets == 0)
445             break;
446         }
447       }
448     if (image->storage_class == DirectClass)
449       image->alpha_trait=pcx_info.planes > 3 ? BlendPixelTrait :
450         UndefinedPixelTrait;
451     else
452       if ((pcx_info.version == 5) ||
453           ((pcx_info.bits_per_pixel*pcx_info.planes) == 1))
454         {
455           /*
456             Initialize image colormap.
457           */
458           if (image->colors > 256)
459             ThrowPCXException(CorruptImageError,"ColormapExceeds256Colors");
460           if ((pcx_info.bits_per_pixel*pcx_info.planes) == 1)
461             {
462               /*
463                 Monochrome colormap.
464               */
465               image->colormap[0].red=(Quantum) 0;
466               image->colormap[0].green=(Quantum) 0;
467               image->colormap[0].blue=(Quantum) 0;
468               image->colormap[1].red=QuantumRange;
469               image->colormap[1].green=QuantumRange;
470               image->colormap[1].blue=QuantumRange;
471             }
472           else
473             if (image->colors > 16)
474               {
475                 /*
476                   256 color images have their color map at the end of the file.
477                 */
478                 pcx_info.colormap_signature=(unsigned char) ReadBlobByte(image);
479                 count=ReadBlob(image,3*image->colors,pcx_colormap);
480                 p=pcx_colormap;
481                 for (i=0; i < (ssize_t) image->colors; i++)
482                 {
483                   image->colormap[i].red=ScaleCharToQuantum(*p++);
484                   image->colormap[i].green=ScaleCharToQuantum(*p++);
485                   image->colormap[i].blue=ScaleCharToQuantum(*p++);
486                 }
487             }
488         }
489     /*
490       Convert PCX raster image to pixel packets.
491     */
492     for (y=0; y < (ssize_t) image->rows; y++)
493     {
494       p=pixels+(y*pcx_info.bytes_per_line*pcx_info.planes);
495       q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);
496       if (q == (Quantum *) NULL)
497         break;
498       r=scanline;
499       if (image->storage_class == DirectClass)
500         for (i=0; i < pcx_info.planes; i++)
501         {
502           r=scanline+i;
503           for (x=0; x < (ssize_t) pcx_info.bytes_per_line; x++)
504           {
505             switch (i)
506             {
507               case 0:
508               {
509                 *r=(*p++);
510                 break;
511               }
512               case 1:
513               {
514                 *r=(*p++);
515                 break;
516               }
517               case 2:
518               {
519                 *r=(*p++);
520                 break;
521               }
522               case 3:
523               default:
524               {
525                 *r=(*p++);
526                 break;
527               }
528             }
529             r+=pcx_info.planes;
530           }
531         }
532       else
533         if (pcx_info.planes > 1)
534           {
535             for (x=0; x < (ssize_t) image->columns; x++)
536               *r++=0;
537             for (i=0; i < pcx_info.planes; i++)
538             {
539               r=scanline;
540               for (x=0; x < (ssize_t) pcx_info.bytes_per_line; x++)
541               {
542                  bits=(*p++);
543                  for (mask=0x80; mask != 0; mask>>=1)
544                  {
545                    if (bits & mask)
546                      *r|=1 << i;
547                    r++;
548                  }
549                }
550             }
551           }
552         else
553           switch (pcx_info.bits_per_pixel)
554           {
555             case 1:
556             {
557               register ssize_t
558                 bit;
559
560               for (x=0; x < ((ssize_t) image->columns-7); x+=8)
561               {
562                 for (bit=7; bit >= 0; bit--)
563                   *r++=(unsigned char) ((*p) & (0x01 << bit) ? 0x01 : 0x00);
564                 p++;
565               }
566               if ((image->columns % 8) != 0)
567                 {
568                   for (bit=7; bit >= (ssize_t) (8-(image->columns % 8)); bit--)
569                     *r++=(unsigned char) ((*p) & (0x01 << bit) ? 0x01 : 0x00);
570                   p++;
571                 }
572               break;
573             }
574             case 2:
575             {
576               for (x=0; x < ((ssize_t) image->columns-3); x+=4)
577               {
578                 *r++=(*p >> 6) & 0x3;
579                 *r++=(*p >> 4) & 0x3;
580                 *r++=(*p >> 2) & 0x3;
581                 *r++=(*p) & 0x3;
582                 p++;
583               }
584               if ((image->columns % 4) != 0)
585                 {
586                   for (i=3; i >= (ssize_t) (4-(image->columns % 4)); i--)
587                     *r++=(unsigned char) ((*p >> (i*2)) & 0x03);
588                   p++;
589                 }
590               break;
591             }
592             case 4:
593             {
594               for (x=0; x < ((ssize_t) image->columns-1); x+=2)
595               {
596                 *r++=(*p >> 4) & 0xf;
597                 *r++=(*p) & 0xf;
598                 p++;
599               }
600               if ((image->columns % 2) != 0)
601                 *r++=(*p++ >> 4) & 0xf;
602               break;
603             }
604             case 8:
605             {
606               (void) CopyMagickMemory(r,p,image->columns);
607               break;
608             }
609             default:
610               break;
611           }
612       /*
613         Transfer image scanline.
614       */
615       r=scanline;
616       for (x=0; x < (ssize_t) image->columns; x++)
617       {
618         if (image->storage_class == PseudoClass)
619           SetPixelIndex(image,*r++,q);
620         else
621           {
622             SetPixelRed(image,ScaleCharToQuantum(*r++),q);
623             SetPixelGreen(image,ScaleCharToQuantum(*r++),q);
624             SetPixelBlue(image,ScaleCharToQuantum(*r++),q);
625             if (image->alpha_trait != UndefinedPixelTrait)
626               SetPixelAlpha(image,ScaleCharToQuantum(*r++),q);
627           }
628         q+=GetPixelChannels(image);
629       }
630       if (SyncAuthenticPixels(image,exception) == MagickFalse)
631         break;
632       if (image->previous == (Image *) NULL)
633         {
634           status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y,
635             image->rows);
636           if (status == MagickFalse)
637             break;
638         }
639     }
640     if (image->storage_class == PseudoClass)
641       (void) SyncImage(image,exception);
642     scanline=(unsigned char *) RelinquishMagickMemory(scanline);
643     pixel_info=RelinquishVirtualMemory(pixel_info);
644     if (EOFBlob(image) != MagickFalse)
645       {
646         ThrowFileException(exception,CorruptImageError,"UnexpectedEndOfFile",
647           image->filename);
648         break;
649       }
650     /*
651       Proceed to next image.
652     */
653     if (image_info->number_scenes != 0)
654       if (image->scene >= (image_info->scene+image_info->number_scenes-1))
655         break;
656     if (page_table == (MagickOffsetType *) NULL)
657       break;
658     if (page_table[id] == 0)
659       break;
660     offset=SeekBlob(image,(MagickOffsetType) page_table[id],SEEK_SET);
661     if (offset < 0)
662       ThrowReaderException(CorruptImageError,"ImproperImageHeader");
663     count=ReadBlob(image,1,&pcx_info.identifier);
664     if ((count != 0) && (pcx_info.identifier == 0x0a))
665       {
666         /*
667           Allocate next image structure.
668         */
669         AcquireNextImage(image_info,image,exception);
670         if (GetNextImageInList(image) == (Image *) NULL)
671           {
672             image=DestroyImageList(image);
673             return((Image *) NULL);
674           }
675         image=SyncNextImageInList(image);
676         status=SetImageProgress(image,LoadImagesTag,TellBlob(image),
677           GetBlobSize(image));
678         if (status == MagickFalse)
679           break;
680       }
681   }
682   if (page_table != (MagickOffsetType *) NULL)
683     page_table=(MagickOffsetType *) RelinquishMagickMemory(page_table);
684   (void) CloseBlob(image);
685   return(GetFirstImageInList(image));
686 }
687 \f
688 /*
689 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
690 %                                                                             %
691 %                                                                             %
692 %                                                                             %
693 %   R e g i s t e r P C X I m a g e                                           %
694 %                                                                             %
695 %                                                                             %
696 %                                                                             %
697 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
698 %
699 %  RegisterPCXImage() adds attributes for the PCX image format to
700 %  the list of supported formats.  The attributes include the image format
701 %  tag, a method to read and/or write the format, whether the format
702 %  supports the saving of more than one frame to the same file or blob,
703 %  whether the format supports native in-memory I/O, and a brief
704 %  description of the format.
705 %
706 %  The format of the RegisterPCXImage method is:
707 %
708 %      size_t RegisterPCXImage(void)
709 %
710 */
711 ModuleExport size_t RegisterPCXImage(void)
712 {
713   MagickInfo
714     *entry;
715
716   entry=AcquireMagickInfo("PCX","DCX","ZSoft IBM PC multi-page Paintbrush");
717   entry->decoder=(DecodeImageHandler *) ReadPCXImage;
718   entry->encoder=(EncodeImageHandler *) WritePCXImage;
719   entry->flags|=CoderDecoderSeekableStreamFlag;
720   entry->flags|=CoderEncoderSeekableStreamFlag;
721   entry->magick=(IsImageFormatHandler *) IsDCX;
722   (void) RegisterMagickInfo(entry);
723   entry=AcquireMagickInfo("PCX","PCX","ZSoft IBM PC Paintbrush");
724   entry->decoder=(DecodeImageHandler *) ReadPCXImage;
725   entry->encoder=(EncodeImageHandler *) WritePCXImage;
726   entry->magick=(IsImageFormatHandler *) IsPCX;
727   entry->flags^=CoderAdjoinFlag;
728   entry->flags|=CoderDecoderSeekableStreamFlag;
729   entry->flags|=CoderEncoderSeekableStreamFlag;
730   (void) RegisterMagickInfo(entry);
731   return(MagickImageCoderSignature);
732 }
733 \f
734 /*
735 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
736 %                                                                             %
737 %                                                                             %
738 %                                                                             %
739 %   U n r e g i s t e r P C X I m a g e                                       %
740 %                                                                             %
741 %                                                                             %
742 %                                                                             %
743 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
744 %
745 %  UnregisterPCXImage() removes format registrations made by the
746 %  PCX module from the list of supported formats.
747 %
748 %  The format of the UnregisterPCXImage method is:
749 %
750 %      UnregisterPCXImage(void)
751 %
752 */
753 ModuleExport void UnregisterPCXImage(void)
754 {
755   (void) UnregisterMagickInfo("DCX");
756   (void) UnregisterMagickInfo("PCX");
757 }
758 \f
759 /*
760 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
761 %                                                                             %
762 %                                                                             %
763 %                                                                             %
764 %   W r i t e P C X I m a g e                                                 %
765 %                                                                             %
766 %                                                                             %
767 %                                                                             %
768 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
769 %
770 %  WritePCXImage() writes an image in the ZSoft IBM PC Paintbrush file
771 %  format.
772 %
773 %  The format of the WritePCXImage method is:
774 %
775 %      MagickBooleanType WritePCXImage(const ImageInfo *image_info,
776 %        Image *image,ExceptionInfo *exception)
777 %
778 %  A description of each parameter follows.
779 %
780 %    o image_info: the image info.
781 %
782 %    o image:  The image.
783 %
784 %    o exception: return any errors or warnings in this structure.
785 %
786 */
787
788 static MagickBooleanType PCXWritePixels(PCXInfo *pcx_info,
789   const unsigned char *pixels,Image *image)
790 {
791   register const unsigned char
792     *q;
793
794   register ssize_t
795     i,
796     x;
797
798   ssize_t
799     count;
800
801   unsigned char
802     packet,
803     previous;
804
805   q=pixels;
806   for (i=0; i < (ssize_t) pcx_info->planes; i++)
807   {
808     if (pcx_info->encoding == 0)
809       {
810         for (x=0; x < (ssize_t) pcx_info->bytes_per_line; x++)
811           (void) WriteBlobByte(image,(unsigned char) (*q++));
812       }
813     else
814       {
815         previous=(*q++);
816         count=1;
817         for (x=0; x < (ssize_t) (pcx_info->bytes_per_line-1); x++)
818         {
819           packet=(*q++);
820           if ((packet == previous) && (count < 63))
821             {
822               count++;
823               continue;
824             }
825           if ((count > 1) || ((previous & 0xc0) == 0xc0))
826             {
827               count|=0xc0;
828               (void) WriteBlobByte(image,(unsigned char) count);
829             }
830           (void) WriteBlobByte(image,previous);
831           previous=packet;
832           count=1;
833         }
834         if ((count > 1) || ((previous & 0xc0) == 0xc0))
835           {
836             count|=0xc0;
837             (void) WriteBlobByte(image,(unsigned char) count);
838           }
839         (void) WriteBlobByte(image,previous);
840       }
841   }
842   return (MagickTrue);
843 }
844
845 static MagickBooleanType WritePCXImage(const ImageInfo *image_info,Image *image,
846   ExceptionInfo *exception)
847 {
848   MagickBooleanType
849     status;
850
851   MagickOffsetType
852     offset,
853     *page_table,
854     scene;
855
856   MemoryInfo
857     *pixel_info;
858
859   PCXInfo
860     pcx_info;
861
862   register const Quantum
863     *p;
864
865   register ssize_t
866     i,
867     x;
868
869   register unsigned char
870     *q;
871
872   size_t
873     length;
874
875   ssize_t
876     y;
877
878   unsigned char
879     *pcx_colormap,
880     *pixels;
881
882   /*
883     Open output image file.
884   */
885   assert(image_info != (const ImageInfo *) NULL);
886   assert(image_info->signature == MagickCoreSignature);
887   assert(image != (Image *) NULL);
888   assert(image->signature == MagickCoreSignature);
889   if (image->debug != MagickFalse)
890     (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
891   assert(exception != (ExceptionInfo *) NULL);
892   assert(exception->signature == MagickCoreSignature);
893   status=OpenBlob(image_info,image,WriteBinaryBlobMode,exception);
894   if (status == MagickFalse)
895     return(status);
896   (void) TransformImageColorspace(image,sRGBColorspace,exception);
897   page_table=(MagickOffsetType *) NULL;
898   if ((LocaleCompare(image_info->magick,"DCX") == 0) ||
899       ((GetNextImageInList(image) != (Image *) NULL) &&
900        (image_info->adjoin != MagickFalse)))
901     {
902       /*
903         Write the DCX page table.
904       */
905       (void) WriteBlobLSBLong(image,0x3ADE68B1L);
906       page_table=(MagickOffsetType *) AcquireQuantumMemory(1024UL,
907         sizeof(*page_table));
908       if (page_table == (MagickOffsetType *) NULL)
909         ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed");
910       for (scene=0; scene < 1024; scene++)
911         (void) WriteBlobLSBLong(image,0x00000000L);
912     }
913   scene=0;
914   do
915   {
916     if (page_table != (MagickOffsetType *) NULL)
917       page_table[scene]=TellBlob(image);
918     /*
919       Initialize PCX raster file header.
920     */
921     pcx_info.identifier=0x0a;
922     pcx_info.version=5;
923     pcx_info.encoding=image_info->compression == NoCompression ? 0 : 1;
924     pcx_info.bits_per_pixel=8;
925     if ((image->storage_class == PseudoClass) &&
926         (SetImageMonochrome(image,exception) != MagickFalse))
927       pcx_info.bits_per_pixel=1;
928     pcx_info.left=0;
929     pcx_info.top=0;
930     pcx_info.right=(unsigned short) (image->columns-1);
931     pcx_info.bottom=(unsigned short) (image->rows-1);
932     switch (image->units)
933     {
934       case UndefinedResolution:
935       case PixelsPerInchResolution:
936       default:
937       {
938         pcx_info.horizontal_resolution=(unsigned short) image->resolution.x;
939         pcx_info.vertical_resolution=(unsigned short) image->resolution.y;
940         break;
941       }
942       case PixelsPerCentimeterResolution:
943       {
944         pcx_info.horizontal_resolution=(unsigned short)
945           (2.54*image->resolution.x+0.5);
946         pcx_info.vertical_resolution=(unsigned short)
947           (2.54*image->resolution.y+0.5);
948         break;
949       }
950     }
951     pcx_info.reserved=0;
952     pcx_info.planes=1;
953     if ((image->storage_class == DirectClass) || (image->colors > 256))
954       {
955         pcx_info.planes=3;
956         if (image->alpha_trait != UndefinedPixelTrait)
957           pcx_info.planes++;
958       }
959     pcx_info.bytes_per_line=(unsigned short) (((size_t) image->columns*
960       pcx_info.bits_per_pixel+7)/8);
961     pcx_info.palette_info=1;
962     pcx_info.colormap_signature=0x0c;
963     /*
964       Write PCX header.
965     */
966     (void) WriteBlobByte(image,pcx_info.identifier);
967     (void) WriteBlobByte(image,pcx_info.version);
968     (void) WriteBlobByte(image,pcx_info.encoding);
969     (void) WriteBlobByte(image,pcx_info.bits_per_pixel);
970     (void) WriteBlobLSBShort(image,pcx_info.left);
971     (void) WriteBlobLSBShort(image,pcx_info.top);
972     (void) WriteBlobLSBShort(image,pcx_info.right);
973     (void) WriteBlobLSBShort(image,pcx_info.bottom);
974     (void) WriteBlobLSBShort(image,pcx_info.horizontal_resolution);
975     (void) WriteBlobLSBShort(image,pcx_info.vertical_resolution);
976     /*
977       Dump colormap to file.
978     */
979     pcx_colormap=(unsigned char *) AcquireQuantumMemory(256UL,
980       3*sizeof(*pcx_colormap));
981     if (pcx_colormap == (unsigned char *) NULL)
982       ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed");
983     (void) memset(pcx_colormap,0,3*256*sizeof(*pcx_colormap));
984     q=pcx_colormap;
985     if ((image->storage_class == PseudoClass) && (image->colors <= 256))
986       for (i=0; i < (ssize_t) image->colors; i++)
987       {
988         *q++=ScaleQuantumToChar(image->colormap[i].red);
989         *q++=ScaleQuantumToChar(image->colormap[i].green);
990         *q++=ScaleQuantumToChar(image->colormap[i].blue);
991       }
992     (void) WriteBlob(image,3*16,(const unsigned char *) pcx_colormap);
993     (void) WriteBlobByte(image,pcx_info.reserved);
994     (void) WriteBlobByte(image,pcx_info.planes);
995     (void) WriteBlobLSBShort(image,pcx_info.bytes_per_line);
996     (void) WriteBlobLSBShort(image,pcx_info.palette_info);
997     for (i=0; i < 58; i++)
998       (void) WriteBlobByte(image,'\0');
999     length=(size_t) pcx_info.bytes_per_line;
1000     pixel_info=AcquireVirtualMemory(length,pcx_info.planes*sizeof(*pixels));
1001     if (pixel_info == (MemoryInfo *) NULL)
1002       ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed");
1003     pixels=(unsigned char *) GetVirtualMemoryBlob(pixel_info);
1004     q=pixels;
1005     if ((image->storage_class == DirectClass) || (image->colors > 256))
1006       {
1007         /*
1008           Convert DirectClass image to PCX raster pixels.
1009         */
1010         for (y=0; y < (ssize_t) image->rows; y++)
1011         {
1012           q=pixels;
1013           for (i=0; i < pcx_info.planes; i++)
1014           {
1015             p=GetVirtualPixels(image,0,y,image->columns,1,exception);
1016             if (p == (const Quantum *) NULL)
1017               break;
1018             switch ((int) i)
1019             {
1020               case 0:
1021               {
1022                 for (x=0; x < (ssize_t) pcx_info.bytes_per_line; x++)
1023                 {
1024                   *q++=ScaleQuantumToChar(GetPixelRed(image,p));
1025                   p+=GetPixelChannels(image);
1026                 }
1027                 break;
1028               }
1029               case 1:
1030               {
1031                 for (x=0; x < (ssize_t) pcx_info.bytes_per_line; x++)
1032                 {
1033                   *q++=ScaleQuantumToChar(GetPixelGreen(image,p));
1034                   p+=GetPixelChannels(image);
1035                 }
1036                 break;
1037               }
1038               case 2:
1039               {
1040                 for (x=0; x < (ssize_t) pcx_info.bytes_per_line; x++)
1041                 {
1042                   *q++=ScaleQuantumToChar(GetPixelBlue(image,p));
1043                   p+=GetPixelChannels(image);
1044                 }
1045                 break;
1046               }
1047               case 3:
1048               default:
1049               {
1050                 for (x=(ssize_t) pcx_info.bytes_per_line; x != 0; x--)
1051                 {
1052                   *q++=ScaleQuantumToChar((Quantum) (GetPixelAlpha(image,p)));
1053                   p+=GetPixelChannels(image);
1054                 }
1055                 break;
1056               }
1057             }
1058           }
1059           if (PCXWritePixels(&pcx_info,pixels,image) == MagickFalse)
1060             break;
1061           if (image->previous == (Image *) NULL)
1062             {
1063               status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y,
1064                 image->rows);
1065               if (status == MagickFalse)
1066                 break;
1067             }
1068         }
1069       }
1070     else
1071       {
1072         if (pcx_info.bits_per_pixel > 1)
1073           for (y=0; y < (ssize_t) image->rows; y++)
1074           {
1075             p=GetVirtualPixels(image,0,y,image->columns,1,exception);
1076             if (p == (const Quantum *) NULL)
1077               break;
1078             q=pixels;
1079             for (x=0; x < (ssize_t) image->columns; x++)
1080             {
1081               *q++=(unsigned char) GetPixelIndex(image,p);
1082               p+=GetPixelChannels(image);
1083             }
1084             if (PCXWritePixels(&pcx_info,pixels,image) == MagickFalse)
1085               break;
1086             if (image->previous == (Image *) NULL)
1087               {
1088                 status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y,
1089                 image->rows);
1090                 if (status == MagickFalse)
1091                   break;
1092               }
1093           }
1094         else
1095           {
1096             register unsigned char
1097               bit,
1098               byte;
1099
1100             /*
1101               Convert PseudoClass image to a PCX monochrome image.
1102             */
1103             for (y=0; y < (ssize_t) image->rows; y++)
1104             {
1105               p=GetVirtualPixels(image,0,y,image->columns,1,exception);
1106               if (p == (const Quantum *) NULL)
1107                 break;
1108               bit=0;
1109               byte=0;
1110               q=pixels;
1111               for (x=0; x < (ssize_t) image->columns; x++)
1112               {
1113                 byte<<=1;
1114                 if (GetPixelLuma(image,p) >= (QuantumRange/2.0))
1115                   byte|=0x01;
1116                 bit++;
1117                 if (bit == 8)
1118                   {
1119                     *q++=byte;
1120                     bit=0;
1121                     byte=0;
1122                   }
1123                 p+=GetPixelChannels(image);
1124               }
1125               if (bit != 0)
1126                 *q++=byte << (8-bit);
1127               if (PCXWritePixels(&pcx_info,pixels,image) == MagickFalse)
1128                 break;
1129               if (image->previous == (Image *) NULL)
1130                 {
1131                   status=SetImageProgress(image,SaveImageTag,(MagickOffsetType)
1132                     y,image->rows);
1133                   if (status == MagickFalse)
1134                     break;
1135                 }
1136             }
1137           }
1138         (void) WriteBlobByte(image,pcx_info.colormap_signature);
1139         (void) WriteBlob(image,3*256,pcx_colormap);
1140       }
1141     pixel_info=RelinquishVirtualMemory(pixel_info);
1142     pcx_colormap=(unsigned char *) RelinquishMagickMemory(pcx_colormap);
1143     if (page_table == (MagickOffsetType *) NULL)
1144       break;
1145     if (scene >= 1023)
1146       break;
1147     if (GetNextImageInList(image) == (Image *) NULL)
1148       break;
1149     image=SyncNextImageInList(image);
1150     status=SetImageProgress(image,SaveImagesTag,scene++,
1151       GetImageListLength(image));
1152     if (status == MagickFalse)
1153       break;
1154   } while (image_info->adjoin != MagickFalse);
1155   if (page_table != (MagickOffsetType *) NULL)
1156     {
1157       /*
1158         Write the DCX page table.
1159       */
1160       page_table[scene+1]=0;
1161       offset=SeekBlob(image,0L,SEEK_SET);
1162       if (offset < 0)
1163         ThrowWriterException(CorruptImageError,"ImproperImageHeader");
1164       (void) WriteBlobLSBLong(image,0x3ADE68B1L);
1165       for (i=0; i <= (ssize_t) scene; i++)
1166         (void) WriteBlobLSBLong(image,(unsigned int) page_table[i]);
1167       page_table=(MagickOffsetType *) RelinquishMagickMemory(page_table);
1168     }
1169   if (status == MagickFalse)
1170     {
1171       char
1172         *message;
1173
1174       message=GetExceptionMessage(errno);
1175       (void) ThrowMagickException(exception,GetMagickModule(),FileOpenError,
1176         "UnableToWriteFile","`%s': %s",image->filename,message);
1177       message=DestroyString(message);
1178     }
1179   (void) CloseBlob(image);
1180   return(MagickTrue);
1181 }