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