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