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