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