]> 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   count=ReadBlob(image,3,(unsigned char *) tag);
357   if (count != 3  ||  memcmp(tag,"\x6f\x80\x00",3) != 0)
358     ThrowReaderException(CorruptImageError,"CorruptImage");
359
360   if (pdb_info.number_records > 1)
361     {
362       comment_offset=(int) ReadBlobMSBLong(image);
363       attributes=(unsigned char) ReadBlobByte(image);
364       count=ReadBlob(image,3,(unsigned char *) tag);
365       if (count != 3  ||  memcmp(tag,"\x6f\x80\x01",3) != 0)
366         ThrowReaderException(CorruptImageError,"CorruptImage");
367     }
368
369   num_pad_bytes = (size_t) (img_offset - TellBlob( image ));
370   while (num_pad_bytes--) ReadBlobByte( image );
371   /*
372     Read image header.
373   */
374   count=ReadBlob(image,32,(unsigned char *) pdb_image.name);
375   pdb_image.version=ReadBlobByte(image);
376   pdb_image.type=ReadBlobByte(image);
377   pdb_image.reserved_1=ReadBlobMSBLong(image);
378   pdb_image.note=ReadBlobMSBLong(image);
379   pdb_image.x_last=(short) ReadBlobMSBShort(image);
380   pdb_image.y_last=(short) ReadBlobMSBShort(image);
381   pdb_image.reserved_2=ReadBlobMSBLong(image);
382   pdb_image.x_anchor=(short) ReadBlobMSBShort(image);
383   pdb_image.y_anchor=(short) ReadBlobMSBShort(image);
384   pdb_image.width=(short) ReadBlobMSBShort(image);
385   pdb_image.height=(short) ReadBlobMSBShort(image);
386   /*
387     Initialize image structure.
388   */
389   image->columns=(size_t) pdb_image.width;
390   image->rows=(size_t) pdb_image.height;
391   image->depth=8;
392   image->storage_class=PseudoClass;
393   bits_per_pixel=pdb_image.type == 0 ? 2UL : pdb_image.type == 2 ? 4UL : 1UL;
394   one=1;
395   if (AcquireImageColormap(image,one << bits_per_pixel) == MagickFalse)
396     ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
397   if (image_info->ping != MagickFalse)
398     {
399       (void) CloseBlob(image);
400       return(GetFirstImageInList(image));
401     }
402   packets=bits_per_pixel*image->columns/8;
403   pixels=(unsigned char *) AcquireQuantumMemory(packets+256UL,image->rows*
404     sizeof(*pixels));
405   if (pixels == (unsigned char *) NULL)
406     ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
407
408   switch (pdb_image.version & 7) /* TS */
409   {
410     case 0:
411     {
412       image->compression=NoCompression;
413       count=(ssize_t) ReadBlob(image, packets * image -> rows, pixels);
414       break;
415     }
416     case 1:
417     {
418       image->compression=RLECompression;
419       if (!DecodeImage(image, pixels, packets * image -> rows))
420         ThrowReaderException( CorruptImageError, "RLEDecoderError" ); /* TS */
421       break;
422     }
423     default:
424       ThrowReaderException(CorruptImageError,
425          "UnrecognizedImageCompressionType" );
426   }
427   p=pixels;
428   switch (bits_per_pixel)
429   {
430     case 1:
431     {
432       int
433         bit;
434
435       /*
436         Read 1-bit PDB image.
437       */
438       for (y=0; y < (ssize_t) image->rows; y++)
439       {
440         q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);
441         if (q == (PixelPacket *) NULL)
442           break;
443         indexes=GetAuthenticIndexQueue(image);
444         for (x=0; x < ((ssize_t) image->columns-7); x+=8)
445         {
446           for (bit=0; bit < 8; bit++)
447           {
448             index=(IndexPacket) (*p & (0x80 >> bit) ? 0x00 : 0x01);
449             indexes[x+bit]=index;
450             *q++=image->colormap[(ssize_t) index];
451           }
452           p++;
453         }
454         if (SyncAuthenticPixels(image,exception) == MagickFalse)
455           break;
456         status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y,
457                 image->rows);
458         if (status == MagickFalse)
459           break;
460       }
461       break;
462     }
463     case 2:
464     {
465       /*
466         Read 2-bit PDB image.
467       */
468       for (y=0; y < (ssize_t) image->rows; y++)
469       {
470         q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);
471         if (q == (PixelPacket *) NULL)
472           break;
473         indexes=GetAuthenticIndexQueue(image);
474         for (x=0; x < (ssize_t) image->columns; x+=4)
475         {
476           index=ConstrainColormapIndex(image,3UL-((*p >> 6) & 0x03));
477           indexes[x]=index;
478           *q++=image->colormap[(ssize_t) index];
479           index=ConstrainColormapIndex(image,3UL-((*p >> 4) & 0x03));
480           indexes[x+1]=index;
481           *q++=image->colormap[(ssize_t) index];
482           index=ConstrainColormapIndex(image,3UL-((*p >> 2) & 0x03));
483           indexes[x+2]=index;
484           *q++=image->colormap[(ssize_t) index];
485           index=ConstrainColormapIndex(image,3UL-((*p) & 0x03));
486           indexes[x+3]=index;
487           *q++=image->colormap[(ssize_t) index];
488           p++;
489         }
490         if (SyncAuthenticPixels(image,exception) == MagickFalse)
491           break;
492         status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y,
493                 image->rows);
494         if (status == MagickFalse)
495           break;
496       }
497       break;
498     }
499     case 4:
500     {
501       /*
502         Read 4-bit PDB image.
503       */
504       for (y=0; y < (ssize_t) image->rows; y++)
505       {
506         q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);
507         if (q == (PixelPacket *) NULL)
508           break;
509         indexes=GetAuthenticIndexQueue(image);
510         for (x=0; x < (ssize_t) image->columns; x+=2)
511         {
512           index=ConstrainColormapIndex(image,15UL-((*p >> 4) & 0x0f));
513           indexes[x]=index;
514           *q++=image->colormap[(ssize_t) index];
515           index=ConstrainColormapIndex(image,15UL-((*p) & 0x0f));
516           indexes[x+1]=index;
517           *q++=image->colormap[(ssize_t) index];
518           p++;
519         }
520         if (SyncAuthenticPixels(image,exception) == MagickFalse)
521           break;
522         status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y,
523                 image->rows);
524         if (status == MagickFalse)
525           break;
526       }
527       break;
528     }
529     default:
530       ThrowReaderException(CorruptImageError,"ImproperImageHeader");
531   }
532
533   pixels=(unsigned char *) RelinquishMagickMemory(pixels);
534   if (EOFBlob(image) != MagickFalse)
535     ThrowFileException(exception,CorruptImageError,"UnexpectedEndOfFile",
536       image->filename);
537   if (pdb_info.number_records > 1) /* TS */
538     {
539       char
540         *comment;
541
542       int
543         c;
544
545       register char
546         *p;
547
548       size_t
549         length;
550
551       num_pad_bytes = (size_t) (comment_offset - TellBlob( image ));
552       while (num_pad_bytes--) ReadBlobByte( image );
553
554       /*
555         Read comment.
556       */
557       c=ReadBlobByte(image);
558       length=MaxTextExtent;
559       comment=AcquireString((char *) NULL);
560       for (p=comment; c != EOF; p++)
561       {
562         if ((size_t) (p-comment+MaxTextExtent) >= length)
563           {
564             *p='\0';
565             length<<=1;
566             length+=MaxTextExtent;
567             comment=(char *) ResizeQuantumMemory(comment,length+MaxTextExtent,
568               sizeof(*comment));
569             if (comment == (char *) NULL)
570               break;
571             p=comment+strlen(comment);
572           }
573         *p=c;
574         c=ReadBlobByte(image);
575       }
576       *p='\0';
577       if (comment == (char *) NULL)
578         ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
579       (void) SetImageProperty(image,"comment",comment);
580       comment=DestroyString(comment);
581     }
582   (void) CloseBlob(image);
583   return(GetFirstImageInList(image));
584 }
585 \f
586 /*
587 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
588 %                                                                             %
589 %                                                                             %
590 %                                                                             %
591 %   R e g i s t e r P D B I m a g e                                           %
592 %                                                                             %
593 %                                                                             %
594 %                                                                             %
595 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
596 %
597 %  RegisterPDBImage() adds properties for the PDB image format to
598 %  the list of supported formats.  The properties include the image format
599 %  tag, a method to read and/or write the format, whether the format
600 %  supports the saving of more than one frame to the same file or blob,
601 %  whether the format supports native in-memory I/O, and a brief
602 %  description of the format.
603 %
604 %  The format of the RegisterPDBImage method is:
605 %
606 %      size_t RegisterPDBImage(void)
607 %
608 */
609 ModuleExport size_t RegisterPDBImage(void)
610 {
611   MagickInfo
612     *entry;
613
614   entry=SetMagickInfo("PDB");
615   entry->decoder=(DecodeImageHandler *) ReadPDBImage;
616   entry->encoder=(EncodeImageHandler *) WritePDBImage;
617   entry->magick=(IsImageFormatHandler *) IsPDB;
618   entry->description=ConstantString("Palm Database ImageViewer Format");
619   entry->module=ConstantString("PDB");
620   (void) RegisterMagickInfo(entry);
621   return(MagickImageCoderSignature);
622 }
623 \f
624 /*
625 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
626 %                                                                             %
627 %                                                                             %
628 %                                                                             %
629 %   U n r e g i s t e r P D B I m a g e                                       %
630 %                                                                             %
631 %                                                                             %
632 %                                                                             %
633 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
634 %
635 %  UnregisterPDBImage() removes format registrations made by the
636 %  PDB module from the list of supported formats.
637 %
638 %  The format of the UnregisterPDBImage method is:
639 %
640 %      UnregisterPDBImage(void)
641 %
642 */
643 ModuleExport void UnregisterPDBImage(void)
644 {
645   (void) UnregisterMagickInfo("PDB");
646 }
647 \f
648 /*
649 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
650 %                                                                             %
651 %                                                                             %
652 %                                                                             %
653 %   W r i t e P D B I m a g e                                                 %
654 %                                                                             %
655 %                                                                             %
656 %                                                                             %
657 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
658 %
659 %  WritePDBImage() writes an image
660 %
661 %  The format of the WritePDBImage method is:
662 %
663 %      MagickBooleanType WritePDBImage(const ImageInfo *image_info,Image *image)
664 %
665 %  A description of each parameter follows.
666 %
667 %    o image_info: the image info.
668 %
669 %    o image:  The image.
670 %
671 %
672 */
673
674 static unsigned char *EncodeRLE(unsigned char *destination,
675   unsigned char *source,size_t literal,size_t repeat)
676 {
677   if (literal > 0)
678     *destination++=(unsigned char) (literal-1);
679   (void) CopyMagickMemory(destination,source,literal);
680   destination+=literal;
681   if (repeat > 0)
682     {
683       *destination++=(unsigned char) (0x80 | (repeat-1));
684       *destination++=source[literal];
685     }
686   return(destination);
687 }
688
689 static MagickBooleanType WritePDBImage(const ImageInfo *image_info,Image *image)
690 {
691   const char
692     *comment;
693
694   int
695     bits;
696
697   ssize_t
698     y;
699
700   MagickBooleanType
701     status;
702
703   PDBImage
704     pdb_image;
705
706   PDBInfo
707     pdb_info;
708
709   QuantumInfo
710     *quantum_info;
711
712   register const PixelPacket
713     *p;
714
715   register ssize_t
716     x;
717
718   register unsigned char
719     *q;
720
721   size_t
722     packet_size;
723
724   unsigned char
725     *buffer,
726     *runlength,
727     *scanline;
728
729   size_t
730     bits_per_pixel,
731     literal,
732     packets,
733     repeat;
734
735   /*
736     Open output image file.
737   */
738   assert(image_info != (const ImageInfo *) NULL);
739   assert(image_info->signature == MagickSignature);
740   assert(image != (Image *) NULL);
741   assert(image->signature == MagickSignature);
742   if (image->debug != MagickFalse)
743     (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
744   status=OpenBlob(image_info,image,WriteBinaryBlobMode,&image->exception);
745   if (status == MagickFalse)
746     return(status);
747   if (image->colorspace != RGBColorspace)
748     (void) TransformImageColorspace(image,RGBColorspace);
749
750   if (image -> colors <= 2  ||  GetImageType( image, &image -> exception ) == BilevelType) { /* TS */
751     bits_per_pixel = 1;
752   } else if (image -> colors <= 4) {
753     bits_per_pixel = 2;
754   } else if (image -> colors <= 8) {
755     bits_per_pixel = 3;
756   } else {
757     bits_per_pixel = 4;
758   }
759
760   (void) ResetMagickMemory(pdb_info.name,0,32);
761   (void) CopyMagickString(pdb_info.name,image_info->filename,32);
762   pdb_info.attributes=0;
763   pdb_info.version=0;
764   pdb_info.create_time=time(NULL);
765   pdb_info.modify_time=pdb_info.create_time;
766   pdb_info.archive_time=0;
767   pdb_info.modify_number=0;
768   pdb_info.application_info=0;
769   pdb_info.sort_info=0;
770   (void) CopyMagickMemory(pdb_info.type,"vIMG",4);
771   (void) CopyMagickMemory(pdb_info.id,"View",4);
772   pdb_info.seed=0;
773   pdb_info.next_record=0;
774   comment=GetImageProperty(image,"comment");
775   pdb_info.number_records=(comment == (const char *) NULL ? 1 : 2);
776   (void) WriteBlob(image,32,(unsigned char *) pdb_info.name);
777   (void) WriteBlobMSBShort(image,(unsigned short) pdb_info.attributes);
778   (void) WriteBlobMSBShort(image,(unsigned short) pdb_info.version);
779   (void) WriteBlobMSBLong(image,(unsigned int) pdb_info.create_time);
780   (void) WriteBlobMSBLong(image,(unsigned int) pdb_info.modify_time);
781   (void) WriteBlobMSBLong(image,(unsigned int) pdb_info.archive_time);
782   (void) WriteBlobMSBLong(image,(unsigned int) pdb_info.modify_number);
783   (void) WriteBlobMSBLong(image,(unsigned int) pdb_info.application_info);
784   (void) WriteBlobMSBLong(image,(unsigned int) pdb_info.sort_info);
785   (void) WriteBlob(image,4,(unsigned char *) pdb_info.type);
786   (void) WriteBlob(image,4,(unsigned char *) pdb_info.id);
787   (void) WriteBlobMSBLong(image,(unsigned int) pdb_info.seed);
788   (void) WriteBlobMSBLong(image,(unsigned int) pdb_info.next_record);
789   (void) WriteBlobMSBShort(image,(unsigned short) pdb_info.number_records);
790   (void) CopyMagickString(pdb_image.name,pdb_info.name,32);
791   pdb_image.version=1;  /* RLE Compressed */
792   switch (bits_per_pixel)
793   {
794     case 1: pdb_image.type=(char) 0xff; break;  /* monochrome */
795     case 2: pdb_image.type=(char) 0x00; break;  /* 2 bit gray */
796     default: pdb_image.type=(char) 0x02;  /* 4 bit gray */
797   }
798   pdb_image.reserved_1=0;
799   pdb_image.note=0;
800   pdb_image.x_last=0;
801   pdb_image.y_last=0;
802   pdb_image.reserved_2=0;
803   pdb_image.x_anchor=(short) 0xffff;
804   pdb_image.y_anchor=(short) 0xffff;
805   pdb_image.width=(short) image->columns;
806   if (image->columns % 16)
807     pdb_image.width=(short) (16*(image->columns/16+1));
808   pdb_image.height=(short) image->rows;
809   packets=(bits_per_pixel*image->columns/8)*image->rows;
810   runlength=(unsigned char *) AcquireQuantumMemory(2UL*packets,
811     sizeof(*runlength));
812   if (runlength == (unsigned char *) NULL)
813     ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed");
814   buffer=(unsigned char *) AcquireQuantumMemory(256UL,sizeof(*buffer));
815   if (buffer == (unsigned char *) NULL)
816     ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed");
817   packet_size=(size_t) (image->depth > 8 ? 2: 1);
818   scanline=(unsigned char *) AcquireQuantumMemory(image->columns,packet_size*
819     sizeof(*scanline));
820   if (scanline == (unsigned char *) NULL)
821     ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed");
822   if (image->colorspace != RGBColorspace)
823     (void) TransformImageColorspace(image,RGBColorspace);
824   /*
825     Convert to GRAY raster scanline.
826   */
827   quantum_info=AcquireQuantumInfo(image_info,image);
828   if (quantum_info == (QuantumInfo *) NULL)
829     ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed");
830   bits=8/(int) bits_per_pixel-1;  /* start at most significant bits */
831   literal=0;
832   repeat=0;
833   q=runlength;
834   buffer[0]=0x00;
835   for (y=0; y < (ssize_t) image->rows; y++)
836   {
837     p=GetVirtualPixels(image,0,y,image->columns,1,&image->exception);
838     if (p == (const PixelPacket *) NULL)
839       break;
840     (void) ExportQuantumPixels(image,(const CacheView *) NULL,quantum_info,
841       GrayQuantum,scanline,&image->exception);
842     for (x=0; x < pdb_image.width; x++)
843     {
844       if (x < (ssize_t) image->columns)
845         buffer[literal+repeat]|=(0xff-scanline[x*packet_size]) >>
846           (8-bits_per_pixel) << bits*bits_per_pixel;
847       bits--;
848       if (bits < 0)
849         {
850           if (((literal+repeat) > 0) &&
851               (buffer[literal+repeat] == buffer[literal+repeat-1]))
852             {
853               if (repeat == 0)
854                 {
855                   literal--;
856                   repeat++;
857                 }
858               repeat++;
859               if (0x7f < repeat)
860                 {
861                   q=EncodeRLE(q,buffer,literal,repeat);
862                   literal=0;
863                   repeat=0;
864                 }
865             }
866           else
867             {
868               if (repeat >= 2)
869                 literal+=repeat;
870               else
871                 {
872                   q=EncodeRLE(q,buffer,literal,repeat);
873                   buffer[0]=buffer[literal+repeat];
874                   literal=0;
875                 }
876               literal++;
877               repeat=0;
878               if (0x7f < literal)
879                 {
880                   q=EncodeRLE(q,buffer,(literal < 0x80 ? literal : 0x80),0);
881                   (void) CopyMagickMemory(buffer,buffer+literal+repeat,0x80);
882                   literal-=0x80;
883                 }
884             }
885         bits=8/(int) bits_per_pixel-1;
886         buffer[literal+repeat]=0x00;
887       }
888     }
889     status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y,
890                 image->rows);
891     if (status == MagickFalse)
892       break;
893   }
894   q=EncodeRLE(q,buffer,literal,repeat);
895   scanline=(unsigned char *) RelinquishMagickMemory(scanline);
896   buffer=(unsigned char *) RelinquishMagickMemory(buffer);
897   quantum_info=DestroyQuantumInfo(quantum_info);
898   /*
899     Write the Image record header.
900   */
901   (void) WriteBlobMSBLong(image,(unsigned int)
902     (TellBlob(image)+8*pdb_info.number_records));
903   (void) WriteBlobByte(image,0x40);
904   (void) WriteBlobByte(image,0x6f);
905   (void) WriteBlobByte(image,0x80);
906   (void) WriteBlobByte(image,0);
907   if (pdb_info.number_records > 1)
908     {
909       /*
910         Write the comment record header.
911       */
912       (void) WriteBlobMSBLong(image,(unsigned int) (TellBlob(image)+8+58+q-
913         runlength));
914       (void) WriteBlobByte(image,0x40);
915       (void) WriteBlobByte(image,0x6f);
916       (void) WriteBlobByte(image,0x80);
917       (void) WriteBlobByte(image,1);
918     }
919   /*
920     Write the Image data.
921   */
922   (void) WriteBlob(image,32,(unsigned char *) pdb_image.name);
923   (void) WriteBlobByte(image,(unsigned char) pdb_image.version);
924   (void) WriteBlobByte(image,(unsigned char) pdb_image.type);
925   (void) WriteBlobMSBLong(image,(unsigned int) pdb_image.reserved_1);
926   (void) WriteBlobMSBLong(image,(unsigned int) pdb_image.note);
927   (void) WriteBlobMSBShort(image,(unsigned short) pdb_image.x_last);
928   (void) WriteBlobMSBShort(image,(unsigned short) pdb_image.y_last);
929   (void) WriteBlobMSBLong(image,(unsigned int) pdb_image.reserved_2);
930   (void) WriteBlobMSBShort(image,(unsigned short) pdb_image.x_anchor);
931   (void) WriteBlobMSBShort(image,(unsigned short) pdb_image.y_anchor);
932   (void) WriteBlobMSBShort(image,(unsigned short) pdb_image.width);
933   (void) WriteBlobMSBShort(image,(unsigned short) pdb_image.height);
934   (void) WriteBlob(image,(size_t) (q-runlength),runlength);
935   runlength=(unsigned char *) RelinquishMagickMemory(runlength);
936   if (pdb_info.number_records > 1)
937     (void) WriteBlobString(image,comment);
938   (void) CloseBlob(image);
939   return(MagickTrue);
940 }