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