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