]> granicus.if.org Git - imagemagick/blob - coders/pdb.c
(no commit message)
[imagemagick] / coders / pdb.c
1 /*
2 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
3 %                                                                             %
4 %                                                                             %
5 %                                                                             %
6 %                            PPPP   DDDD   BBBB                               %
7 %                            P   P  D   D  B   B                              %
8 %                            PPPP   D   D  BBBB                               %
9 %                            P      D   D  B   B                              %
10 %                            P      DDDD   BBBB                               %
11 %                                                                             %
12 %                                                                             %
13 %               Read/Write Palm Database ImageViewer Image Format             %
14 %                                                                             %
15 %                              Software Design                                %
16 %                                John Cristy                                  %
17 %                                 July 1992                                   %
18 %                                                                             %
19 %                                                                             %
20 %  Copyright 1999-2011 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     20071202 TS * rewrote RLE decoder - old version could cause buffer overflows
38                 * failure of RLE decoding now thows error RLEDecoderError
39                 * fixed bug in RLE decoding - now all rows are decoded, not just
40       the first one
41     * fixed bug in reader - record offsets now handled correctly
42     * fixed bug in reader - only bits 0..2 indicate compression type
43                 * in writer: now using image color count instead of depth
44 */
45 \f
46 /*
47   Include declarations.
48 */
49 #include "magick/studio.h"
50 #include "magick/attribute.h"
51 #include "magick/blob.h"
52 #include "magick/blob-private.h"
53 #include "magick/cache.h"
54 #include "magick/colormap-private.h"
55 #include "magick/color-private.h"
56 #include "magick/colormap.h"
57 #include "magick/colorspace.h"
58 #include "magick/constitute.h"
59 #include "magick/exception.h"
60 #include "magick/exception-private.h"
61 #include "magick/image.h"
62 #include "magick/image-private.h"
63 #include "magick/list.h"
64 #include "magick/magick.h"
65 #include "magick/memory_.h"
66 #include "magick/monitor.h"
67 #include "magick/monitor-private.h"
68 #include "magick/property.h"
69 #include "magick/quantum-private.h"
70 #include "magick/quantum-private.h"
71 #include "magick/static.h"
72 #include "magick/string_.h"
73 #include "magick/module.h"
74 \f
75 /*
76   Typedef declarations.
77 */
78 typedef struct _PDBInfo
79 {
80   char
81     name[32];
82
83   short int
84     attributes,
85     version;
86
87   size_t
88     create_time,
89     modify_time,
90     archive_time,
91     modify_number,
92     application_info,
93     sort_info;
94
95   char
96     type[4],  /* database type identifier "vIMG" */
97     id[4];    /* database creator identifier "View" */
98
99   size_t
100     seed,
101     next_record;
102
103   short int
104     number_records;
105 } PDBInfo;
106
107 typedef struct _PDBImage
108 {
109   char
110     name[32],
111     version,
112     type;
113
114   size_t
115     reserved_1,
116     note;
117
118   short int
119     x_last,
120     y_last;
121
122   size_t
123     reserved_2;
124
125   short int
126     x_anchor,
127     y_anchor,
128     width,
129     height;
130 } PDBImage;
131 /*
132   Forward declarations.
133 */
134 static MagickBooleanType
135   WritePDBImage(const ImageInfo *,Image *);
136 \f
137 /*
138 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
139 %                                                                             %
140 %                                                                             %
141 %                                                                             %
142 %   D e c o d e I m a g e                                                     %
143 %                                                                             %
144 %                                                                             %
145 %                                                                             %
146 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
147 %
148 %  DecodeImage unpacks the packed image pixels into runlength-encoded
149 %  pixel packets.
150 %
151 %  The format of the DecodeImage method is:
152 %
153 %      MagickBooleanType DecodeImage(Image *image,unsigned char *pixels,
154 %        const size_t length)
155 %
156 %  A description of each parameter follows:
157 %
158 %    o image: the address of a structure of type Image.
159 %
160 %    o pixels:  The address of a byte (8 bits) array of pixel data created by
161 %      the decoding process.
162 %
163 %    o length:  Number of bytes to read into buffer 'pixels'.
164 %
165 */
166 static MagickBooleanType DecodeImage(Image *image, unsigned char *pixels,
167   const size_t length)
168 {
169 #define RLE_MODE_NONE -1
170 #define RLE_MODE_COPY  0
171 #define RLE_MODE_RUN   1
172
173   int           data = 0, count = 0;
174   unsigned char *p;
175   int           mode = RLE_MODE_NONE;
176
177   for (p = pixels; p < pixels + length; p++) {
178     if (0 == count) {
179       data = ReadBlobByte( image );
180       if (-1 == data) return MagickFalse;
181       if (data > 128) {
182         mode  = RLE_MODE_RUN;
183         count = data - 128 + 1;
184         data  = ReadBlobByte( image );
185         if (-1 == data) return MagickFalse;
186       } else {
187         mode  = RLE_MODE_COPY;
188         count = data + 1;
189       }
190     }
191
192     if (RLE_MODE_COPY == mode) {
193       data = ReadBlobByte( image );
194       if (-1 == data) return MagickFalse;
195     }
196     *p = (unsigned char)data;
197     --count;
198   }
199   return MagickTrue;
200 }
201 \f
202 /*
203 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
204 %                                                                             %
205 %                                                                             %
206 %                                                                             %
207 %   I s P D B                                                                 %
208 %                                                                             %
209 %                                                                             %
210 %                                                                             %
211 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
212 %
213 %  IsPDB() returns MagickTrue if the image format type, identified by the
214 %  magick string, is PDB.
215 %
216 %  The format of the ReadPDBImage method is:
217 %
218 %      MagickBooleanType IsPDB(const unsigned char *magick,const size_t length)
219 %
220 %  A description of each parameter follows:
221 %
222 %    o magick: compare image format pattern against these bytes.
223 %
224 %    o length: Specifies the length of the magick string.
225 %
226 */
227 static MagickBooleanType IsPDB(const unsigned char *magick,const size_t length)
228 {
229   if (length < 68)
230     return(MagickFalse);
231   if (memcmp(magick+60,"vIMGView",8) == 0)
232     return(MagickTrue);
233   return(MagickFalse);
234 }
235 \f
236 /*
237 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
238 %                                                                             %
239 %                                                                             %
240 %                                                                             %
241 %   R e a d P D B I m a g e                                                   %
242 %                                                                             %
243 %                                                                             %
244 %                                                                             %
245 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
246 %
247 %  ReadPDBImage() reads an Pilot image file and returns it.  It
248 %  allocates the memory necessary for the new Image structure and returns a
249 %  pointer to the new image.
250 %
251 %  The format of the ReadPDBImage method is:
252 %
253 %      Image *ReadPDBImage(const ImageInfo *image_info,ExceptionInfo *exception)
254 %
255 %  A description of each parameter follows:
256 %
257 %    o image_info: the image info.
258 %
259 %    o exception: return any errors or warnings in this structure.
260 %
261 */
262 static Image *ReadPDBImage(const ImageInfo *image_info,ExceptionInfo *exception)
263 {
264   unsigned char
265     attributes, /* TS */
266     tag[3];
267
268   Image
269     *image;
270
271   IndexPacket
272     index;
273
274   ssize_t
275     img_offset, /* TS */
276     comment_offset = 0,
277     y;
278
279   MagickBooleanType
280     status;
281
282   PDBImage
283     pdb_image;
284
285   PDBInfo
286     pdb_info;
287
288   register IndexPacket
289     *indexes;
290
291   register ssize_t
292     x;
293
294   register PixelPacket
295     *q;
296
297   register unsigned char
298     *p;
299
300   ssize_t
301     count;
302
303   unsigned char
304     *pixels;
305
306   size_t
307     bits_per_pixel,
308     num_pad_bytes, /* TS */
309     one,
310     packets;
311
312   /*
313     Open image file.
314   */
315   assert(image_info != (const ImageInfo *) NULL);
316   assert(image_info->signature == MagickSignature);
317   if (image_info->debug != MagickFalse)
318     (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",
319       image_info->filename);
320   assert(exception != (ExceptionInfo *) NULL);
321   assert(exception->signature == MagickSignature);
322   image=AcquireImage(image_info);
323   status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception);
324   if (status == MagickFalse)
325     {
326       image=DestroyImageList(image);
327       return((Image *) NULL);
328     }
329   /*
330     Determine if this a PDB image file.
331   */
332   count=ReadBlob(image,32,(unsigned char *) pdb_info.name);
333   pdb_info.attributes=(short) ReadBlobMSBShort(image);
334   pdb_info.version=(short) ReadBlobMSBShort(image);
335   pdb_info.create_time=ReadBlobMSBLong(image);
336   pdb_info.modify_time=ReadBlobMSBLong(image);
337   pdb_info.archive_time=ReadBlobMSBLong(image);
338   pdb_info.modify_number=ReadBlobMSBLong(image);
339   pdb_info.application_info=ReadBlobMSBLong(image);
340   pdb_info.sort_info=ReadBlobMSBLong(image);
341   count=ReadBlob(image,4,(unsigned char *) pdb_info.type);
342   count=ReadBlob(image,4,(unsigned char *) pdb_info.id);
343   if ((count == 0) || (memcmp(pdb_info.type,"vIMG",4) != 0) ||
344       (memcmp(pdb_info.id,"View",4) != 0))
345     ThrowReaderException(CorruptImageError,"ImproperImageHeader");
346   pdb_info.seed=ReadBlobMSBLong(image);
347   pdb_info.next_record=ReadBlobMSBLong(image);
348   pdb_info.number_records=(short) ReadBlobMSBShort(image);
349   if (pdb_info.next_record != 0)
350     ThrowReaderException(CoderError,"MultipleRecordListNotSupported");
351   /*
352     Read record header.
353   */
354   img_offset=(int) ReadBlobMSBLong(image); /* TS */
355   attributes=(unsigned char) ReadBlobByte(image);
356   (void) attributes;
357   count=ReadBlob(image,3,(unsigned char *) tag);
358   if (count != 3  ||  memcmp(tag,"\x6f\x80\x00",3) != 0)
359     ThrowReaderException(CorruptImageError,"CorruptImage");
360
361   if (pdb_info.number_records > 1)
362     {
363       comment_offset=(int) ReadBlobMSBLong(image);
364       attributes=(unsigned char) ReadBlobByte(image);
365       count=ReadBlob(image,3,(unsigned char *) tag);
366       if (count != 3  ||  memcmp(tag,"\x6f\x80\x01",3) != 0)
367         ThrowReaderException(CorruptImageError,"CorruptImage");
368     }
369
370   num_pad_bytes = (size_t) (img_offset - TellBlob( image ));
371   while (num_pad_bytes--) ReadBlobByte( image );
372   /*
373     Read image header.
374   */
375   count=ReadBlob(image,32,(unsigned char *) pdb_image.name);
376   pdb_image.version=ReadBlobByte(image);
377   pdb_image.type=ReadBlobByte(image);
378   pdb_image.reserved_1=ReadBlobMSBLong(image);
379   pdb_image.note=ReadBlobMSBLong(image);
380   pdb_image.x_last=(short) ReadBlobMSBShort(image);
381   pdb_image.y_last=(short) ReadBlobMSBShort(image);
382   pdb_image.reserved_2=ReadBlobMSBLong(image);
383   pdb_image.x_anchor=(short) ReadBlobMSBShort(image);
384   pdb_image.y_anchor=(short) ReadBlobMSBShort(image);
385   pdb_image.width=(short) ReadBlobMSBShort(image);
386   pdb_image.height=(short) ReadBlobMSBShort(image);
387   /*
388     Initialize image structure.
389   */
390   image->columns=(size_t) pdb_image.width;
391   image->rows=(size_t) pdb_image.height;
392   image->depth=8;
393   image->storage_class=PseudoClass;
394   bits_per_pixel=pdb_image.type == 0 ? 2UL : pdb_image.type == 2 ? 4UL : 1UL;
395   one=1;
396   if (AcquireImageColormap(image,one << bits_per_pixel) == MagickFalse)
397     ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
398   if (image_info->ping != MagickFalse)
399     {
400       (void) CloseBlob(image);
401       return(GetFirstImageInList(image));
402     }
403   packets=bits_per_pixel*image->columns/8;
404   pixels=(unsigned char *) AcquireQuantumMemory(packets+256UL,image->rows*
405     sizeof(*pixels));
406   if (pixels == (unsigned char *) NULL)
407     ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
408
409   switch (pdb_image.version & 7) /* TS */
410   {
411     case 0:
412     {
413       image->compression=NoCompression;
414       count=(ssize_t) ReadBlob(image, packets * image -> rows, pixels);
415       break;
416     }
417     case 1:
418     {
419       image->compression=RLECompression;
420       if (!DecodeImage(image, pixels, packets * image -> rows))
421         ThrowReaderException( CorruptImageError, "RLEDecoderError" ); /* TS */
422       break;
423     }
424     default:
425       ThrowReaderException(CorruptImageError,
426          "UnrecognizedImageCompressionType" );
427   }
428   p=pixels;
429   switch (bits_per_pixel)
430   {
431     case 1:
432     {
433       int
434         bit;
435
436       /*
437         Read 1-bit PDB image.
438       */
439       for (y=0; y < (ssize_t) image->rows; y++)
440       {
441         q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);
442         if (q == (PixelPacket *) NULL)
443           break;
444         indexes=GetAuthenticIndexQueue(image);
445         for (x=0; x < ((ssize_t) image->columns-7); x+=8)
446         {
447           for (bit=0; bit < 8; bit++)
448           {
449             index=(IndexPacket) (*p & (0x80 >> bit) ? 0x00 : 0x01);
450             SetIndexPixelComponent(indexes+x+bit,index);
451             *q++=image->colormap[(ssize_t) index];
452           }
453           p++;
454         }
455         if (SyncAuthenticPixels(image,exception) == MagickFalse)
456           break;
457         status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y,
458                 image->rows);
459         if (status == MagickFalse)
460           break;
461       }
462       break;
463     }
464     case 2:
465     {
466       /*
467         Read 2-bit PDB image.
468       */
469       for (y=0; y < (ssize_t) image->rows; y++)
470       {
471         q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);
472         if (q == (PixelPacket *) NULL)
473           break;
474         indexes=GetAuthenticIndexQueue(image);
475         for (x=0; x < (ssize_t) image->columns; x+=4)
476         {
477           index=ConstrainColormapIndex(image,3UL-((*p >> 6) & 0x03));
478           indexes[x]=index;
479           *q++=image->colormap[(ssize_t) index];
480           index=ConstrainColormapIndex(image,3UL-((*p >> 4) & 0x03));
481           indexes[x+1]=index;
482           *q++=image->colormap[(ssize_t) index];
483           index=ConstrainColormapIndex(image,3UL-((*p >> 2) & 0x03));
484           indexes[x+2]=index;
485           *q++=image->colormap[(ssize_t) index];
486           index=ConstrainColormapIndex(image,3UL-((*p) & 0x03));
487           indexes[x+3]=index;
488           *q++=image->colormap[(ssize_t) index];
489           p++;
490         }
491         if (SyncAuthenticPixels(image,exception) == MagickFalse)
492           break;
493         status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y,
494                 image->rows);
495         if (status == MagickFalse)
496           break;
497       }
498       break;
499     }
500     case 4:
501     {
502       /*
503         Read 4-bit PDB image.
504       */
505       for (y=0; y < (ssize_t) image->rows; y++)
506       {
507         q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);
508         if (q == (PixelPacket *) NULL)
509           break;
510         indexes=GetAuthenticIndexQueue(image);
511         for (x=0; x < (ssize_t) image->columns; x+=2)
512         {
513           index=ConstrainColormapIndex(image,15UL-((*p >> 4) & 0x0f));
514           indexes[x]=index;
515           *q++=image->colormap[(ssize_t) index];
516           index=ConstrainColormapIndex(image,15UL-((*p) & 0x0f));
517           indexes[x+1]=index;
518           *q++=image->colormap[(ssize_t) index];
519           p++;
520         }
521         if (SyncAuthenticPixels(image,exception) == MagickFalse)
522           break;
523         status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y,
524                 image->rows);
525         if (status == MagickFalse)
526           break;
527       }
528       break;
529     }
530     default:
531       ThrowReaderException(CorruptImageError,"ImproperImageHeader");
532   }
533
534   pixels=(unsigned char *) RelinquishMagickMemory(pixels);
535   if (EOFBlob(image) != MagickFalse)
536     ThrowFileException(exception,CorruptImageError,"UnexpectedEndOfFile",
537       image->filename);
538   if (pdb_info.number_records > 1) /* TS */
539     {
540       char
541         *comment;
542
543       int
544         c;
545
546       register char
547         *p;
548
549       size_t
550         length;
551
552       num_pad_bytes = (size_t) (comment_offset - TellBlob( image ));
553       while (num_pad_bytes--) ReadBlobByte( image );
554
555       /*
556         Read comment.
557       */
558       c=ReadBlobByte(image);
559       length=MaxTextExtent;
560       comment=AcquireString((char *) NULL);
561       for (p=comment; c != EOF; p++)
562       {
563         if ((size_t) (p-comment+MaxTextExtent) >= length)
564           {
565             *p='\0';
566             length<<=1;
567             length+=MaxTextExtent;
568             comment=(char *) ResizeQuantumMemory(comment,length+MaxTextExtent,
569               sizeof(*comment));
570             if (comment == (char *) NULL)
571               break;
572             p=comment+strlen(comment);
573           }
574         *p=c;
575         c=ReadBlobByte(image);
576       }
577       *p='\0';
578       if (comment == (char *) NULL)
579         ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
580       (void) SetImageProperty(image,"comment",comment);
581       comment=DestroyString(comment);
582     }
583   (void) CloseBlob(image);
584   return(GetFirstImageInList(image));
585 }
586 \f
587 /*
588 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
589 %                                                                             %
590 %                                                                             %
591 %                                                                             %
592 %   R e g i s t e r P D B I m a g e                                           %
593 %                                                                             %
594 %                                                                             %
595 %                                                                             %
596 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
597 %
598 %  RegisterPDBImage() adds properties for the PDB image format to
599 %  the list of supported formats.  The properties include the image format
600 %  tag, a method to read and/or write the format, whether the format
601 %  supports the saving of more than one frame to the same file or blob,
602 %  whether the format supports native in-memory I/O, and a brief
603 %  description of the format.
604 %
605 %  The format of the RegisterPDBImage method is:
606 %
607 %      size_t RegisterPDBImage(void)
608 %
609 */
610 ModuleExport size_t RegisterPDBImage(void)
611 {
612   MagickInfo
613     *entry;
614
615   entry=SetMagickInfo("PDB");
616   entry->decoder=(DecodeImageHandler *) ReadPDBImage;
617   entry->encoder=(EncodeImageHandler *) WritePDBImage;
618   entry->magick=(IsImageFormatHandler *) IsPDB;
619   entry->description=ConstantString("Palm Database ImageViewer Format");
620   entry->module=ConstantString("PDB");
621   (void) RegisterMagickInfo(entry);
622   return(MagickImageCoderSignature);
623 }
624 \f
625 /*
626 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
627 %                                                                             %
628 %                                                                             %
629 %                                                                             %
630 %   U n r e g i s t e r P D B I m a g e                                       %
631 %                                                                             %
632 %                                                                             %
633 %                                                                             %
634 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
635 %
636 %  UnregisterPDBImage() removes format registrations made by the
637 %  PDB module from the list of supported formats.
638 %
639 %  The format of the UnregisterPDBImage method is:
640 %
641 %      UnregisterPDBImage(void)
642 %
643 */
644 ModuleExport void UnregisterPDBImage(void)
645 {
646   (void) UnregisterMagickInfo("PDB");
647 }
648 \f
649 /*
650 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
651 %                                                                             %
652 %                                                                             %
653 %                                                                             %
654 %   W r i t e P D B I m a g e                                                 %
655 %                                                                             %
656 %                                                                             %
657 %                                                                             %
658 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
659 %
660 %  WritePDBImage() writes an image
661 %
662 %  The format of the WritePDBImage method is:
663 %
664 %      MagickBooleanType WritePDBImage(const ImageInfo *image_info,Image *image)
665 %
666 %  A description of each parameter follows.
667 %
668 %    o image_info: the image info.
669 %
670 %    o image:  The image.
671 %
672 %
673 */
674
675 static unsigned char *EncodeRLE(unsigned char *destination,
676   unsigned char *source,size_t literal,size_t repeat)
677 {
678   if (literal > 0)
679     *destination++=(unsigned char) (literal-1);
680   (void) CopyMagickMemory(destination,source,literal);
681   destination+=literal;
682   if (repeat > 0)
683     {
684       *destination++=(unsigned char) (0x80 | (repeat-1));
685       *destination++=source[literal];
686     }
687   return(destination);
688 }
689
690 static MagickBooleanType WritePDBImage(const ImageInfo *image_info,Image *image)
691 {
692   const char
693     *comment;
694
695   int
696     bits;
697
698   ssize_t
699     y;
700
701   MagickBooleanType
702     status;
703
704   PDBImage
705     pdb_image;
706
707   PDBInfo
708     pdb_info;
709
710   QuantumInfo
711     *quantum_info;
712
713   register const PixelPacket
714     *p;
715
716   register ssize_t
717     x;
718
719   register unsigned char
720     *q;
721
722   size_t
723     packet_size;
724
725   unsigned char
726     *buffer,
727     *runlength,
728     *scanline;
729
730   size_t
731     bits_per_pixel,
732     literal,
733     packets,
734     repeat;
735
736   /*
737     Open output image file.
738   */
739   assert(image_info != (const ImageInfo *) NULL);
740   assert(image_info->signature == MagickSignature);
741   assert(image != (Image *) NULL);
742   assert(image->signature == MagickSignature);
743   if (image->debug != MagickFalse)
744     (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
745   status=OpenBlob(image_info,image,WriteBinaryBlobMode,&image->exception);
746   if (status == MagickFalse)
747     return(status);
748   if (image->colorspace != RGBColorspace)
749     (void) TransformImageColorspace(image,RGBColorspace);
750
751   if (image -> colors <= 2  ||  GetImageType( image, &image -> exception ) == BilevelType) { /* TS */
752     bits_per_pixel = 1;
753   } else if (image -> colors <= 4) {
754     bits_per_pixel = 2;
755   } else if (image -> colors <= 8) {
756     bits_per_pixel = 3;
757   } else {
758     bits_per_pixel = 4;
759   }
760
761   (void) ResetMagickMemory(pdb_info.name,0,32);
762   (void) CopyMagickString(pdb_info.name,image_info->filename,32);
763   pdb_info.attributes=0;
764   pdb_info.version=0;
765   pdb_info.create_time=time(NULL);
766   pdb_info.modify_time=pdb_info.create_time;
767   pdb_info.archive_time=0;
768   pdb_info.modify_number=0;
769   pdb_info.application_info=0;
770   pdb_info.sort_info=0;
771   (void) CopyMagickMemory(pdb_info.type,"vIMG",4);
772   (void) CopyMagickMemory(pdb_info.id,"View",4);
773   pdb_info.seed=0;
774   pdb_info.next_record=0;
775   comment=GetImageProperty(image,"comment");
776   pdb_info.number_records=(comment == (const char *) NULL ? 1 : 2);
777   (void) WriteBlob(image,32,(unsigned char *) pdb_info.name);
778   (void) WriteBlobMSBShort(image,(unsigned short) pdb_info.attributes);
779   (void) WriteBlobMSBShort(image,(unsigned short) pdb_info.version);
780   (void) WriteBlobMSBLong(image,(unsigned int) pdb_info.create_time);
781   (void) WriteBlobMSBLong(image,(unsigned int) pdb_info.modify_time);
782   (void) WriteBlobMSBLong(image,(unsigned int) pdb_info.archive_time);
783   (void) WriteBlobMSBLong(image,(unsigned int) pdb_info.modify_number);
784   (void) WriteBlobMSBLong(image,(unsigned int) pdb_info.application_info);
785   (void) WriteBlobMSBLong(image,(unsigned int) pdb_info.sort_info);
786   (void) WriteBlob(image,4,(unsigned char *) pdb_info.type);
787   (void) WriteBlob(image,4,(unsigned char *) pdb_info.id);
788   (void) WriteBlobMSBLong(image,(unsigned int) pdb_info.seed);
789   (void) WriteBlobMSBLong(image,(unsigned int) pdb_info.next_record);
790   (void) WriteBlobMSBShort(image,(unsigned short) pdb_info.number_records);
791   (void) CopyMagickString(pdb_image.name,pdb_info.name,32);
792   pdb_image.version=1;  /* RLE Compressed */
793   switch (bits_per_pixel)
794   {
795     case 1: pdb_image.type=(char) 0xff; break;  /* monochrome */
796     case 2: pdb_image.type=(char) 0x00; break;  /* 2 bit gray */
797     default: pdb_image.type=(char) 0x02;  /* 4 bit gray */
798   }
799   pdb_image.reserved_1=0;
800   pdb_image.note=0;
801   pdb_image.x_last=0;
802   pdb_image.y_last=0;
803   pdb_image.reserved_2=0;
804   pdb_image.x_anchor=(short) 0xffff;
805   pdb_image.y_anchor=(short) 0xffff;
806   pdb_image.width=(short) image->columns;
807   if (image->columns % 16)
808     pdb_image.width=(short) (16*(image->columns/16+1));
809   pdb_image.height=(short) image->rows;
810   packets=(bits_per_pixel*image->columns/8)*image->rows;
811   runlength=(unsigned char *) AcquireQuantumMemory(2UL*packets,
812     sizeof(*runlength));
813   if (runlength == (unsigned char *) NULL)
814     ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed");
815   buffer=(unsigned char *) AcquireQuantumMemory(256UL,sizeof(*buffer));
816   if (buffer == (unsigned char *) NULL)
817     ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed");
818   packet_size=(size_t) (image->depth > 8 ? 2: 1);
819   scanline=(unsigned char *) AcquireQuantumMemory(image->columns,packet_size*
820     sizeof(*scanline));
821   if (scanline == (unsigned char *) NULL)
822     ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed");
823   if (image->colorspace != RGBColorspace)
824     (void) TransformImageColorspace(image,RGBColorspace);
825   /*
826     Convert to GRAY raster scanline.
827   */
828   quantum_info=AcquireQuantumInfo(image_info,image);
829   if (quantum_info == (QuantumInfo *) NULL)
830     ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed");
831   bits=8/(int) bits_per_pixel-1;  /* start at most significant bits */
832   literal=0;
833   repeat=0;
834   q=runlength;
835   buffer[0]=0x00;
836   for (y=0; y < (ssize_t) image->rows; y++)
837   {
838     p=GetVirtualPixels(image,0,y,image->columns,1,&image->exception);
839     if (p == (const PixelPacket *) NULL)
840       break;
841     (void) ExportQuantumPixels(image,(const CacheView *) NULL,quantum_info,
842       GrayQuantum,scanline,&image->exception);
843     for (x=0; x < pdb_image.width; x++)
844     {
845       if (x < (ssize_t) image->columns)
846         buffer[literal+repeat]|=(0xff-scanline[x*packet_size]) >>
847           (8-bits_per_pixel) << bits*bits_per_pixel;
848       bits--;
849       if (bits < 0)
850         {
851           if (((literal+repeat) > 0) &&
852               (buffer[literal+repeat] == buffer[literal+repeat-1]))
853             {
854               if (repeat == 0)
855                 {
856                   literal--;
857                   repeat++;
858                 }
859               repeat++;
860               if (0x7f < repeat)
861                 {
862                   q=EncodeRLE(q,buffer,literal,repeat);
863                   literal=0;
864                   repeat=0;
865                 }
866             }
867           else
868             {
869               if (repeat >= 2)
870                 literal+=repeat;
871               else
872                 {
873                   q=EncodeRLE(q,buffer,literal,repeat);
874                   buffer[0]=buffer[literal+repeat];
875                   literal=0;
876                 }
877               literal++;
878               repeat=0;
879               if (0x7f < literal)
880                 {
881                   q=EncodeRLE(q,buffer,(literal < 0x80 ? literal : 0x80),0);
882                   (void) CopyMagickMemory(buffer,buffer+literal+repeat,0x80);
883                   literal-=0x80;
884                 }
885             }
886         bits=8/(int) bits_per_pixel-1;
887         buffer[literal+repeat]=0x00;
888       }
889     }
890     status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y,
891                 image->rows);
892     if (status == MagickFalse)
893       break;
894   }
895   q=EncodeRLE(q,buffer,literal,repeat);
896   scanline=(unsigned char *) RelinquishMagickMemory(scanline);
897   buffer=(unsigned char *) RelinquishMagickMemory(buffer);
898   quantum_info=DestroyQuantumInfo(quantum_info);
899   /*
900     Write the Image record header.
901   */
902   (void) WriteBlobMSBLong(image,(unsigned int)
903     (TellBlob(image)+8*pdb_info.number_records));
904   (void) WriteBlobByte(image,0x40);
905   (void) WriteBlobByte(image,0x6f);
906   (void) WriteBlobByte(image,0x80);
907   (void) WriteBlobByte(image,0);
908   if (pdb_info.number_records > 1)
909     {
910       /*
911         Write the comment record header.
912       */
913       (void) WriteBlobMSBLong(image,(unsigned int) (TellBlob(image)+8+58+q-
914         runlength));
915       (void) WriteBlobByte(image,0x40);
916       (void) WriteBlobByte(image,0x6f);
917       (void) WriteBlobByte(image,0x80);
918       (void) WriteBlobByte(image,1);
919     }
920   /*
921     Write the Image data.
922   */
923   (void) WriteBlob(image,32,(unsigned char *) pdb_image.name);
924   (void) WriteBlobByte(image,(unsigned char) pdb_image.version);
925   (void) WriteBlobByte(image,(unsigned char) pdb_image.type);
926   (void) WriteBlobMSBLong(image,(unsigned int) pdb_image.reserved_1);
927   (void) WriteBlobMSBLong(image,(unsigned int) pdb_image.note);
928   (void) WriteBlobMSBShort(image,(unsigned short) pdb_image.x_last);
929   (void) WriteBlobMSBShort(image,(unsigned short) pdb_image.y_last);
930   (void) WriteBlobMSBLong(image,(unsigned int) pdb_image.reserved_2);
931   (void) WriteBlobMSBShort(image,(unsigned short) pdb_image.x_anchor);
932   (void) WriteBlobMSBShort(image,(unsigned short) pdb_image.y_anchor);
933   (void) WriteBlobMSBShort(image,(unsigned short) pdb_image.width);
934   (void) WriteBlobMSBShort(image,(unsigned short) pdb_image.height);
935   (void) WriteBlob(image,(size_t) (q-runlength),runlength);
936   runlength=(unsigned char *) RelinquishMagickMemory(runlength);
937   if (pdb_info.number_records > 1)
938     (void) WriteBlobString(image,comment);
939   (void) CloseBlob(image);
940   return(MagickTrue);
941 }