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