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