]> granicus.if.org Git - imagemagick/blob - coders/dib.c
(no commit message)
[imagemagick] / coders / dib.c
1 /*
2 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
3 %                                                                             %
4 %                                                                             %
5 %                                                                             %
6 %                            DDDD   IIIII  BBBB                               %
7 %                            D   D    I    B   B                              %
8 %                            D   D    I    BBBB                               %
9 %                            D   D    I    B   B                              %
10 %                            DDDD   IIIII  BBBB                               %
11 %                                                                             %
12 %                                                                             %
13 %                   Read/Write Windows DIB Image Format                       %
14 %                                                                             %
15 %                              Software Design                                %
16 %                                John Cristy                                  %
17 %                                 July 1992                                   %
18 %                                                                             %
19 %                                                                             %
20 %  Copyright 1999-2010 ImageMagick Studio LLC, a non-profit organization      %
21 %  dedicated to making software imaging solutions freely available.           %
22 %                                                                             %
23 %  You may not use this file except in compliance with the License.  You may  %
24 %  obtain a copy of the License at                                            %
25 %                                                                             %
26 %    http://www.imagemagick.org/script/license.php                            %
27 %                                                                             %
28 %  Unless required by applicable law or agreed to in writing, software        %
29 %  distributed under the License is distributed on an "AS IS" BASIS,          %
30 %  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.   %
31 %  See the License for the specific language governing permissions and        %
32 %  limitations under the License.                                             %
33 %                                                                             %
34 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
35 %
36 %
37 */
38 \f
39 /*
40   Include declarations.
41 */
42 #include "magick/studio.h"
43 #include "magick/blob.h"
44 #include "magick/blob-private.h"
45 #include "magick/cache.h"
46 #include "magick/color.h"
47 #include "magick/color-private.h"
48 #include "magick/colormap.h"
49 #include "magick/colormap-private.h"
50 #include "magick/colorspace.h"
51 #include "magick/draw.h"
52 #include "magick/exception.h"
53 #include "magick/exception-private.h"
54 #include "magick/geometry.h"
55 #include "magick/image.h"
56 #include "magick/image-private.h"
57 #include "magick/list.h"
58 #include "magick/log.h"
59 #include "magick/magick.h"
60 #include "magick/memory_.h"
61 #include "magick/monitor.h"
62 #include "magick/monitor-private.h"
63 #include "magick/quantum-private.h"
64 #include "magick/static.h"
65 #include "magick/string_.h"
66 #include "magick/module.h"
67 #include "magick/transform.h"
68 \f
69 /*
70   Typedef declarations.
71 */
72 typedef struct _DIBInfo
73 {
74   unsigned long
75     size;
76
77   long
78     width,
79     height;
80
81   unsigned short
82     planes,
83     bits_per_pixel;
84
85   unsigned long
86     compression,
87     image_size,
88     x_pixels,
89     y_pixels,
90     number_colors,
91     red_mask,
92     green_mask,
93     blue_mask,
94     alpha_mask,
95     colors_important;
96
97   long
98     colorspace;
99
100   PointInfo
101     red_primary,
102     green_primary,
103     blue_primary,
104     gamma_scale;
105 } DIBInfo;
106 \f
107 /*
108   Forward declarations.
109 */
110 static MagickBooleanType
111   WriteDIBImage(const ImageInfo *,Image *);
112 \f
113 /*
114 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
115 %                                                                             %
116 %                                                                             %
117 %                                                                             %
118 %   D e c o d e I m a g e                                                     %
119 %                                                                             %
120 %                                                                             %
121 %                                                                             %
122 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
123 %
124 %  DecodeImage unpacks the packed image pixels into runlength-encoded
125 %  pixel packets.
126 %
127 %  The format of the DecodeImage method is:
128 %
129 %      MagickBooleanType DecodeImage(Image *image,
130 %        const MagickBooleanType compression,unsigned char *pixels)
131 %
132 %  A description of each parameter follows:
133 %
134 %    o image: the address of a structure of type Image.
135 %
136 %    o compression:  A value of 1 means the compressed pixels are runlength
137 %      encoded for a 256-color bitmap.  A value of 2 means a 16-color bitmap.
138 %
139 %    o pixels:  The address of a byte (8 bits) array of pixel data created by
140 %      the decoding process.
141 %
142 */
143
144 static inline size_t MagickMin(const size_t x,const size_t y)
145 {
146   if (x < y)
147     return(x);
148   return(y);
149 }
150
151 static MagickBooleanType DecodeImage(Image *image,
152   const MagickBooleanType compression,unsigned char *pixels)
153 {
154 #if !defined(MAGICKCORE_WINDOWS_SUPPORT) || defined(__MINGW32__)
155 #define BI_RGB  0
156 #define BI_RLE8  1
157 #define BI_RLE4  2
158 #define BI_BITFIELDS  3
159 #endif
160
161   int
162     count;
163
164   long
165     y;
166
167   register long
168     i,
169     x;
170
171   register unsigned char
172     *p,
173     *q;
174
175   unsigned char
176     byte;
177
178   assert(image != (Image *) NULL);
179   assert(image->signature == MagickSignature);
180   if (image->debug != MagickFalse)
181     (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
182   assert(pixels != (unsigned char *) NULL);
183   (void) ResetMagickMemory(pixels,0,(size_t) image->columns*image->rows*
184     sizeof(*pixels));
185   byte=0;
186   x=0;
187   p=pixels;
188   q=pixels+(size_t) image->columns*image->rows;
189   for (y=0; y < (long) image->rows; )
190   {
191     if ((p < pixels) || (p >= q))
192       break;
193     count=ReadBlobByte(image);
194     if (count == EOF)
195       break;
196     if (count != 0)
197       {
198         count=(int) MagickMin((size_t) count,(size_t) (q-p));
199         /*
200           Encoded mode.
201         */
202         byte=(unsigned char) ReadBlobByte(image);
203         if (compression == BI_RLE8)
204           {
205             for (i=0; i < count; i++)
206               *p++=(unsigned char) byte;
207           }
208         else
209           {
210             for (i=0; i < count; i++)
211               *p++=(unsigned char)
212                 ((i & 0x01) != 0 ? (byte & 0x0f) : ((byte >> 4) & 0x0f));
213           }
214         x+=count;
215       }
216     else
217       {
218         /*
219           Escape mode.
220         */
221         count=ReadBlobByte(image);
222         if (count == 0x01)
223           return(MagickTrue);
224         switch (count)
225         {
226           case 0x00:
227           {
228             /*
229               End of line.
230             */
231             x=0;
232             y++;
233             p=pixels+y*image->columns;
234             break;
235           }
236           case 0x02:
237           {
238             /*
239               Delta mode.
240             */
241             x+=ReadBlobByte(image);
242             y+=ReadBlobByte(image);
243             p=pixels+y*image->columns+x;
244             break;
245           }
246           default:
247           {
248             /*
249               Absolute mode.
250             */
251             count=(int) MagickMin((size_t) count,(size_t) (q-p));
252             if (compression == BI_RLE8)
253               for (i=0; i < count; i++)
254                 *p++=(unsigned char) ReadBlobByte(image);
255             else
256               for (i=0; i < count; i++)
257               {
258                 if ((i & 0x01) == 0)
259                   byte=(unsigned char) ReadBlobByte(image);
260                 *p++=(unsigned char)
261                   ((i & 0x01) != 0 ? (byte & 0x0f) : ((byte >> 4) & 0x0f));
262               }
263             x+=count;
264             /*
265               Read pad byte.
266             */
267             if (compression == BI_RLE8)
268               {
269                 if ((count & 0x01) != 0)
270                   (void) ReadBlobByte(image);
271               }
272             else
273               if (((count & 0x03) == 1) || ((count & 0x03) == 2))
274                 (void) ReadBlobByte(image);
275             break;
276           }
277         }
278       }
279     if (SetImageProgress(image,LoadImageTag,y,image->rows) == MagickFalse)
280       break;
281   }
282   (void) ReadBlobByte(image);  /* end of line */
283   (void) ReadBlobByte(image);
284   return(MagickTrue);
285 }
286 \f
287 /*
288 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
289 %                                                                             %
290 %                                                                             %
291 %                                                                             %
292 %   E n c o d e I m a g e                                                     %
293 %                                                                             %
294 %                                                                             %
295 %                                                                             %
296 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
297 %
298 %  EncodeImage compresses pixels using a runlength encoded format.
299 %
300 %  The format of the EncodeImage method is:
301 %
302 %    static MagickBooleanType EncodeImage(Image *image,
303 %      const unsigned long bytes_per_line,const unsigned char *pixels,
304 %      unsigned char *compressed_pixels)
305 %
306 %  A description of each parameter follows:
307 %
308 %    o image:  The image.
309 %
310 %    o bytes_per_line: the number of bytes in a scanline of compressed pixels
311 %
312 %    o pixels:  The address of a byte (8 bits) array of pixel data created by
313 %      the compression process.
314 %
315 %    o compressed_pixels:  The address of a byte (8 bits) array of compressed
316 %      pixel data.
317 %
318 */
319 static size_t EncodeImage(Image *image,const unsigned long bytes_per_line,
320   const unsigned char *pixels,unsigned char *compressed_pixels)
321 {
322   long
323     y;
324
325   register const unsigned char
326     *p;
327
328   register long
329     i,
330     x;
331
332   register unsigned char
333     *q;
334
335   /*
336     Runlength encode pixels.
337   */
338   assert(image != (Image *) NULL);
339   assert(image->signature == MagickSignature);
340   if (image->debug != MagickFalse)
341     (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
342   assert(pixels != (const unsigned char *) NULL);
343   assert(compressed_pixels != (unsigned char *) NULL);
344   p=pixels;
345   q=compressed_pixels;
346   i=0;
347   for (y=0; y < (long) image->rows; y++)
348   {
349     for (x=0; x < (long) bytes_per_line; x+=i)
350     {
351       /*
352         Determine runlength.
353       */
354       for (i=1; ((x+i) < (long) bytes_per_line); i++)
355         if ((*(p+i) != *p) || (i == 255))
356           break;
357       *q++=(unsigned char) i;
358       *q++=(*p);
359       p+=i;
360     }
361     /*
362       End of line.
363     */
364     *q++=0x00;
365     *q++=0x00;
366     if (SetImageProgress(image,LoadImageTag,y,image->rows) == MagickFalse)
367       break;
368   }
369   /*
370     End of bitmap.
371   */
372   *q++=0;
373   *q++=0x01;
374   return((size_t) (q-compressed_pixels));
375 }
376 \f
377 /*
378 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
379 %                                                                             %
380 %                                                                             %
381 %                                                                             %
382 %   I s D I B                                                                 %
383 %                                                                             %
384 %                                                                             %
385 %                                                                             %
386 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
387 %
388 %  IsDIB() returns MagickTrue if the image format type, identified by the
389 %  magick string, is DIB.
390 %
391 %  The format of the IsDIB method is:
392 %
393 %      MagickBooleanType IsDIB(const unsigned char *magick,const size_t length)
394 %
395 %  A description of each parameter follows:
396 %
397 %    o magick: compare image format pattern against these bytes.
398 %
399 %    o length: Specifies the length of the magick string.
400 %
401 */
402 static MagickBooleanType IsDIB(const unsigned char *magick,const size_t length)
403 {
404   if (length < 2)
405     return(MagickFalse);
406   if (memcmp(magick,"\050\000",2) == 0)
407     return(MagickTrue);
408   return(MagickFalse);
409 }
410 \f
411 /*
412 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
413 %                                                                             %
414 %                                                                             %
415 %                                                                             %
416 %   R e a d D I B I m a g e                                                   %
417 %                                                                             %
418 %                                                                             %
419 %                                                                             %
420 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
421 %
422 %  ReadDIBImage() reads a Microsoft Windows bitmap image file and
423 %  returns it.  It allocates the memory necessary for the new Image structure
424 %  and returns a pointer to the new image.
425 %
426 %  The format of the ReadDIBImage method is:
427 %
428 %      image=ReadDIBImage(image_info)
429 %
430 %  A description of each parameter follows:
431 %
432 %    o image_info: the image info.
433 %
434 %    o exception: return any errors or warnings in this structure.
435 %
436 */
437
438 static inline long MagickAbsoluteValue(const long x)
439 {
440   if (x < 0)
441     return(-x);
442   return(x);
443 }
444
445 static inline size_t MagickMax(const size_t x,const size_t y)
446 {
447   if (x > y)
448     return(x);
449   return(y);
450 }
451
452 static Image *ReadDIBImage(const ImageInfo *image_info,ExceptionInfo *exception)
453 {
454   DIBInfo
455     dib_info;
456
457   Image
458     *image;
459
460   IndexPacket
461     index;
462
463   long
464     bit,
465     y;
466
467   MagickBooleanType
468     status;
469
470   register IndexPacket
471     *indexes;
472
473   register long
474     x;
475
476   register PixelPacket
477     *q;
478
479   register long
480     i;
481
482   register unsigned char
483     *p;
484
485   size_t
486     length;
487
488   ssize_t
489     count;
490
491   unsigned char
492     *pixels;
493
494   unsigned long
495     bytes_per_line;
496
497   /*
498     Open image file.
499   */
500   assert(image_info != (const ImageInfo *) NULL);
501   assert(image_info->signature == MagickSignature);
502   if (image_info->debug != MagickFalse)
503     (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",
504       image_info->filename);
505   assert(exception != (ExceptionInfo *) NULL);
506   assert(exception->signature == MagickSignature);
507   image=AcquireImage(image_info);
508   status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception);
509   if (status == MagickFalse)
510     {
511       image=DestroyImageList(image);
512       return((Image *) NULL);
513     }
514   /*
515     Determine if this a DIB file.
516   */
517   (void) ResetMagickMemory(&dib_info,0,sizeof(dib_info));
518   dib_info.size=ReadBlobLSBLong(image);
519   if (dib_info.size!=40)
520     ThrowReaderException(CorruptImageError,"ImproperImageHeader");
521   /*
522     Microsoft Windows 3.X DIB image file.
523   */
524   dib_info.width=(short) ReadBlobLSBLong(image);
525   dib_info.height=(short) ReadBlobLSBLong(image);
526   dib_info.planes=ReadBlobLSBShort(image);
527   dib_info.bits_per_pixel=ReadBlobLSBShort(image);
528   dib_info.compression=ReadBlobLSBLong(image);
529   dib_info.image_size=ReadBlobLSBLong(image);
530   dib_info.x_pixels=ReadBlobLSBLong(image);
531   dib_info.y_pixels=ReadBlobLSBLong(image);
532   dib_info.number_colors=ReadBlobLSBLong(image);
533   dib_info.colors_important=ReadBlobLSBLong(image);
534   if ((dib_info.compression == BI_BITFIELDS) &&
535       ((dib_info.bits_per_pixel == 16) || (dib_info.bits_per_pixel == 32)))
536     {
537       dib_info.red_mask=ReadBlobLSBLong(image);
538       dib_info.green_mask=ReadBlobLSBLong(image);
539       dib_info.blue_mask=ReadBlobLSBLong(image);
540     }
541   image->matte=dib_info.bits_per_pixel == 32 ? MagickTrue : MagickFalse;
542   image->columns=(unsigned long) MagickAbsoluteValue(dib_info.width);
543   image->rows=(unsigned long) MagickAbsoluteValue(dib_info.height);
544   image->depth=8;
545   if ((dib_info.number_colors != 0) || (dib_info.bits_per_pixel < 16))
546     {
547       image->storage_class=PseudoClass;
548       image->colors=dib_info.number_colors;
549       if (image->colors == 0)
550         image->colors=1L << dib_info.bits_per_pixel;
551     }
552   if (image_info->size)
553     {
554       RectangleInfo
555         geometry;
556
557       MagickStatusType
558         flags;
559
560       flags=ParseAbsoluteGeometry(image_info->size,&geometry);
561       if (flags & WidthValue)
562         if ((geometry.width != 0) && (geometry.width < image->columns))
563           image->columns=geometry.width;
564       if (flags & HeightValue)
565         if ((geometry.height != 0) && (geometry.height < image->rows))
566           image->rows=geometry.height;
567     }
568   if (image->storage_class == PseudoClass)
569     {
570       size_t
571         length,
572         packet_size;
573
574       unsigned char
575         *dib_colormap;
576
577       /*
578         Read DIB raster colormap.
579       */
580       if (AcquireImageColormap(image,image->colors) == MagickFalse)
581         ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
582       length=(size_t) image->colors;
583       dib_colormap=(unsigned char *) AcquireQuantumMemory(length,
584         4*sizeof(*dib_colormap));
585       if (dib_colormap == (unsigned char *) NULL)
586         ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
587       packet_size=4;
588       count=ReadBlob(image,packet_size*image->colors,dib_colormap);
589       if (count != (ssize_t) (packet_size*image->colors))
590         ThrowReaderException(CorruptImageError,"InsufficientImageDataInFile");
591       p=dib_colormap;
592       for (i=0; i < (long) image->colors; i++)
593       {
594         image->colormap[i].blue=ScaleCharToQuantum(*p++);
595         image->colormap[i].green=ScaleCharToQuantum(*p++);
596         image->colormap[i].red=ScaleCharToQuantum(*p++);
597         if (packet_size == 4)
598           p++;
599       }
600       dib_colormap=(unsigned char *) RelinquishMagickMemory(dib_colormap);
601     }
602   /*
603     Read image data.
604   */
605   if (dib_info.compression == BI_RLE4)
606     dib_info.bits_per_pixel<<=1;
607   bytes_per_line=4*((image->columns*dib_info.bits_per_pixel+31)/32);
608   length=bytes_per_line*image->rows;
609   pixels=(unsigned char *) AcquireQuantumMemory((size_t) image->rows,
610     MagickMax(bytes_per_line,image->columns+256UL)*sizeof(*pixels));
611   if (pixels == (unsigned char *) NULL)
612     ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
613   if ((dib_info.compression == BI_RGB) ||
614       (dib_info.compression == BI_BITFIELDS))
615     {
616       count=ReadBlob(image,length,pixels);
617       if (count != (ssize_t) (length))
618         ThrowReaderException(CorruptImageError,"InsufficientImageDataInFile");
619     }
620   else
621     {
622       /*
623         Convert run-length encoded raster pixels.
624       */
625       status=DecodeImage(image,dib_info.compression ? MagickTrue : MagickFalse,
626         pixels);
627       if (status == MagickFalse)
628         ThrowReaderException(CorruptImageError,"UnableToRunlengthDecodeImage");
629     }
630   /*
631     Initialize image structure.
632   */
633   image->units=PixelsPerCentimeterResolution;
634   image->x_resolution=(double) dib_info.x_pixels/100.0;
635   image->y_resolution=(double) dib_info.y_pixels/100.0;
636   /*
637     Convert DIB raster image to pixel packets.
638   */
639   switch (dib_info.bits_per_pixel)
640   {
641     case 1:
642     {
643       /*
644         Convert bitmap scanline.
645       */
646       for (y=(long) image->rows-1; y >= 0; y--)
647       {
648         p=pixels+(image->rows-y-1)*bytes_per_line;
649         q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);
650         if (q == (PixelPacket *) NULL)
651           break;
652         indexes=GetAuthenticIndexQueue(image);
653         for (x=0; x < ((long) image->columns-7); x+=8)
654         {
655           for (bit=0; bit < 8; bit++)
656           {
657             index=(IndexPacket) ((*p) & (0x80 >> bit) ? 0x01 : 0x00);
658             indexes[x+bit]=index;
659             *q++=image->colormap[(long) index];
660           }
661           p++;
662         }
663         if ((image->columns % 8) != 0)
664           {
665             for (bit=0; bit < (long) (image->columns % 8); bit++)
666             {
667               index=(IndexPacket) ((*p) & (0x80 >> bit) ? 0x01 : 0x00);
668               indexes[x+bit]=index;
669               *q++=image->colormap[(long) index];
670             }
671             p++;
672           }
673         if (SyncAuthenticPixels(image,exception) == MagickFalse)
674           break;
675         if (image->previous == (Image *) NULL)
676           {
677             status=SetImageProgress(image,LoadImageTag,image->rows-y-1,
678               image->rows);
679             if (status == MagickFalse)
680               break;
681           }
682       }
683       break;
684     }
685     case 4:
686     {
687       /*
688         Convert PseudoColor scanline.
689       */
690       for (y=(long) image->rows-1; y >= 0; y--)
691       {
692         p=pixels+(image->rows-y-1)*bytes_per_line;
693         q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);
694         if (q == (PixelPacket *) NULL)
695           break;
696         indexes=GetAuthenticIndexQueue(image);
697         for (x=0; x < ((long) image->columns-1); x+=2)
698         {
699           index=ConstrainColormapIndex(image,(*p >> 4) & 0xf);
700           indexes[x]=index;
701           *q++=image->colormap[(long) index];
702           index=ConstrainColormapIndex(image,*p & 0xf);
703           indexes[x+1]=index;
704           *q++=image->colormap[(long) index];
705           p++;
706         }
707         if ((image->columns % 2) != 0)
708           {
709             index=ConstrainColormapIndex(image,(*p >> 4) & 0xf);
710             indexes[x]=index;
711             *q++=image->colormap[(long) index];
712             p++;
713           }
714         if (SyncAuthenticPixels(image,exception) == MagickFalse)
715           break;
716         if (image->previous == (Image *) NULL)
717           {
718             status=SetImageProgress(image,LoadImageTag,image->rows-y-1,
719               image->rows);
720             if (status == MagickFalse)
721               break;
722           }
723       }
724       break;
725     }
726     case 8:
727     {
728       /*
729         Convert PseudoColor scanline.
730       */
731       if ((dib_info.compression == BI_RLE8) ||
732           (dib_info.compression == BI_RLE4))
733         bytes_per_line=image->columns;
734       for (y=(long) image->rows-1; y >= 0; y--)
735       {
736         p=pixels+(image->rows-y-1)*bytes_per_line;
737         q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);
738         if (q == (PixelPacket *) NULL)
739           break;
740         indexes=GetAuthenticIndexQueue(image);
741         for (x=0; x < (long) image->columns; x++)
742         {
743           index=ConstrainColormapIndex(image,*p);
744           indexes[x]=index;
745           *q=image->colormap[(long) index];
746           p++;
747           q++;
748         }
749         if (SyncAuthenticPixels(image,exception) == MagickFalse)
750           break;
751         if (image->previous == (Image *) NULL)
752           {
753             status=SetImageProgress(image,LoadImageTag,image->rows-y-1,
754               image->rows);
755             if (status == MagickFalse)
756               break;
757           }
758       }
759       break;
760     }
761     case 16:
762     {
763       unsigned short
764         word;
765
766       /*
767         Convert PseudoColor scanline.
768       */
769       image->storage_class=DirectClass;
770       if (dib_info.compression == BI_RLE8)
771         bytes_per_line=2*image->columns;
772       for (y=(long) image->rows-1; y >= 0; y--)
773       {
774         p=pixels+(image->rows-y-1)*bytes_per_line;
775         q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);
776         if (q == (PixelPacket *) NULL)
777           break;
778         for (x=0; x < (long) image->columns; x++)
779         {
780           word=(*p++);
781           word|=(*p++ << 8);
782           if (dib_info.red_mask == 0)
783             {
784               q->red=ScaleCharToQuantum(ScaleColor5to8((unsigned char)
785                 ((word >> 10) & 0x1f)));
786               q->green=ScaleCharToQuantum(ScaleColor5to8((unsigned char)
787                 ((word >> 5) & 0x1f)));
788               q->blue=ScaleCharToQuantum(ScaleColor5to8((unsigned char)
789                 (word & 0x1f)));
790             }
791           else
792             {
793               q->red=ScaleCharToQuantum(ScaleColor5to8((unsigned char)
794                 ((word >> 11) & 0x1f)));
795               q->green=ScaleCharToQuantum(ScaleColor6to8((unsigned char)
796                 ((word >> 5) & 0x3f)));
797               q->blue=ScaleCharToQuantum(ScaleColor5to8((unsigned char)
798                 (word & 0x1f)));
799             }
800           q++;
801         }
802         if (SyncAuthenticPixels(image,exception) == MagickFalse)
803           break;
804         if (image->previous == (Image *) NULL)
805           {
806             status=SetImageProgress(image,LoadImageTag,image->rows-y-1,
807               image->rows);
808             if (status == MagickFalse)
809               break;
810           }
811       }
812       break;
813     }
814     case 24:
815     case 32:
816     {
817       /*
818         Convert DirectColor scanline.
819       */
820       for (y=(long) image->rows-1; y >= 0; y--)
821       {
822         p=pixels+(image->rows-y-1)*bytes_per_line;
823         q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);
824         if (q == (PixelPacket *) NULL)
825           break;
826         for (x=0; x < (long) image->columns; x++)
827         {
828           q->blue=ScaleCharToQuantum(*p++);
829           q->green=ScaleCharToQuantum(*p++);
830           q->red=ScaleCharToQuantum(*p++);
831           if (image->matte != MagickFalse)
832             q->opacity=ScaleCharToQuantum(*p++);
833           q++;
834         }
835         if (SyncAuthenticPixels(image,exception) == MagickFalse)
836           break;
837         if (image->previous == (Image *) NULL)
838           {
839             status=SetImageProgress(image,LoadImageTag,image->rows-y-1,
840               image->rows);
841             if (status == MagickFalse)
842               break;
843           }
844       }
845       break;
846     }
847     default:
848       ThrowReaderException(CorruptImageError,"ImproperImageHeader");
849   }
850   pixels=(unsigned char *) RelinquishMagickMemory(pixels);
851   if (EOFBlob(image) != MagickFalse)
852     ThrowFileException(exception,CorruptImageError,"UnexpectedEndOfFile",
853       image->filename);
854   if (dib_info.height < 0)
855     {
856       Image
857         *flipped_image;
858
859       /*
860         Correct image orientation.
861       */
862       flipped_image=FlipImage(image,exception);
863       if (flipped_image != (Image *) NULL)
864         {
865           DuplicateBlob(flipped_image,image);
866           image=DestroyImage(image);
867           image=flipped_image;
868         }
869     }
870   (void) CloseBlob(image);
871   return(GetFirstImageInList(image));
872 }
873 \f
874 /*
875 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
876 %                                                                             %
877 %                                                                             %
878 %                                                                             %
879 %   R e g i s t e r D I B I m a g e                                           %
880 %                                                                             %
881 %                                                                             %
882 %                                                                             %
883 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
884 %
885 %  RegisterDIBImage() adds attributes for the DIB image format to
886 %  the list of supported formats.  The attributes include the image format
887 %  tag, a method to read and/or write the format, whether the format
888 %  supports the saving of more than one frame to the same file or blob,
889 %  whether the format supports native in-memory I/O, and a brief
890 %  description of the format.
891 %
892 %  The format of the RegisterDIBImage method is:
893 %
894 %      unsigned long RegisterDIBImage(void)
895 %
896 */
897 ModuleExport unsigned long RegisterDIBImage(void)
898 {
899   MagickInfo
900     *entry;
901
902   entry=SetMagickInfo("DIB");
903   entry->decoder=(DecodeImageHandler *) ReadDIBImage;
904   entry->encoder=(EncodeImageHandler *) WriteDIBImage;
905   entry->magick=(IsImageFormatHandler *) IsDIB;
906   entry->adjoin=MagickFalse;
907   entry->stealth=MagickTrue;
908   entry->description=ConstantString(
909     "Microsoft Windows 3.X Packed Device-Independent Bitmap");
910   entry->module=ConstantString("DIB");
911   (void) RegisterMagickInfo(entry);
912   return(MagickImageCoderSignature);
913 }
914 \f
915 /*
916 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
917 %                                                                             %
918 %                                                                             %
919 %                                                                             %
920 %   U n r e g i s t e r D I B I m a g e                                       %
921 %                                                                             %
922 %                                                                             %
923 %                                                                             %
924 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
925 %
926 %  UnregisterDIBImage() removes format registrations made by the
927 %  DIB module from the list of supported formats.
928 %
929 %  The format of the UnregisterDIBImage method is:
930 %
931 %      UnregisterDIBImage(void)
932 %
933 */
934 ModuleExport void UnregisterDIBImage(void)
935 {
936   (void) UnregisterMagickInfo("DIB");
937 }
938 \f
939 /*
940 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
941 %                                                                             %
942 %                                                                             %
943 %                                                                             %
944 %   W r i t e D I B I m a g e                                                 %
945 %                                                                             %
946 %                                                                             %
947 %                                                                             %
948 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
949 %
950 %  WriteDIBImage() writes an image in Microsoft Windows bitmap encoded
951 %  image format.
952 %
953 %  The format of the WriteDIBImage method is:
954 %
955 %      MagickBooleanType WriteDIBImage(const ImageInfo *image_info,Image *image)
956 %
957 %  A description of each parameter follows.
958 %
959 %    o image_info: the image info.
960 %
961 %    o image:  The image.
962 %
963 */
964 static MagickBooleanType WriteDIBImage(const ImageInfo *image_info,Image *image)
965 {
966   DIBInfo
967     dib_info;
968
969   long
970     y;
971
972   MagickBooleanType
973     status;
974
975   register const IndexPacket
976     *indexes;
977
978   register const PixelPacket
979     *p;
980
981   register long
982     i,
983     x;
984
985   register unsigned char
986     *q;
987
988   unsigned char
989     *dib_data,
990     *pixels;
991
992   unsigned long
993     bytes_per_line;
994
995   /*
996     Open output image file.
997   */
998   assert(image_info != (const ImageInfo *) NULL);
999   assert(image_info->signature == MagickSignature);
1000   assert(image != (Image *) NULL);
1001   assert(image->signature == MagickSignature);
1002   if (image->debug != MagickFalse)
1003     (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
1004   status=OpenBlob(image_info,image,WriteBinaryBlobMode,&image->exception);
1005   if (status == MagickFalse)
1006     return(status);
1007   /*
1008     Initialize DIB raster file header.
1009   */
1010   if (image->colorspace != RGBColorspace)
1011     (void) TransformImageColorspace(image,RGBColorspace);
1012   if (image->storage_class == DirectClass)
1013     {
1014       /*
1015         Full color DIB raster.
1016       */
1017       dib_info.number_colors=0;
1018       dib_info.bits_per_pixel=(unsigned short) (image->matte ? 32 : 24);
1019     }
1020   else
1021     {
1022       /*
1023         Colormapped DIB raster.
1024       */
1025       dib_info.bits_per_pixel=8;
1026       if (image_info->depth > 8)
1027         dib_info.bits_per_pixel=16;
1028       if (IsMonochromeImage(image,&image->exception) != MagickFalse)
1029         dib_info.bits_per_pixel=1;
1030       dib_info.number_colors=(dib_info.bits_per_pixel == 16) ? 0 :
1031         (1UL << dib_info.bits_per_pixel);
1032     }
1033   bytes_per_line=4*((image->columns*dib_info.bits_per_pixel+31)/32);
1034   dib_info.size=40;
1035   dib_info.width=(long) image->columns;
1036   dib_info.height=(long) image->rows;
1037   dib_info.planes=1;
1038   dib_info.compression=(unsigned long) (dib_info.bits_per_pixel == 16 ?
1039     BI_BITFIELDS : BI_RGB);
1040   dib_info.image_size=bytes_per_line*image->rows;
1041   dib_info.x_pixels=75*39;
1042   dib_info.y_pixels=75*39;
1043   switch (image->units)
1044   {
1045     case UndefinedResolution:
1046     case PixelsPerInchResolution:
1047     {
1048       dib_info.x_pixels=(unsigned long) (100.0*image->x_resolution/2.54);
1049       dib_info.y_pixels=(unsigned long) (100.0*image->y_resolution/2.54);
1050       break;
1051     }
1052     case PixelsPerCentimeterResolution:
1053     {
1054       dib_info.x_pixels=(unsigned long) (100.0*image->x_resolution);
1055       dib_info.y_pixels=(unsigned long) (100.0*image->y_resolution);
1056       break;
1057     }
1058   }
1059   dib_info.colors_important=dib_info.number_colors;
1060   /*
1061     Convert MIFF to DIB raster pixels.
1062   */
1063   pixels=(unsigned char *) AcquireQuantumMemory(dib_info.image_size,
1064     sizeof(*pixels));
1065   if (pixels == (unsigned char *) NULL)
1066     ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed");
1067   (void) ResetMagickMemory(pixels,0,dib_info.image_size);
1068   switch (dib_info.bits_per_pixel)
1069   {
1070     case 1:
1071     {
1072       register unsigned char
1073         bit,
1074         byte;
1075
1076       /*
1077         Convert PseudoClass image to a DIB monochrome image.
1078       */
1079       for (y=0; y < (long) image->rows; y++)
1080       {
1081         p=GetVirtualPixels(image,0,y,image->columns,1,&image->exception);
1082         if (p == (const PixelPacket *) NULL)
1083           break;
1084         indexes=GetVirtualIndexQueue(image);
1085         q=pixels+(image->rows-y-1)*bytes_per_line;
1086         bit=0;
1087         byte=0;
1088         for (x=0; x < (long) image->columns; x++)
1089         {
1090           byte<<=1;
1091           byte|=indexes[x] != 0 ? 0x01 : 0x00;
1092           bit++;
1093           if (bit == 8)
1094             {
1095               *q++=byte;
1096               bit=0;
1097               byte=0;
1098             }
1099            p++;
1100          }
1101          if (bit != 0)
1102            {
1103              *q++=(unsigned char) (byte << (8-bit));
1104              x++;
1105            }
1106         for (x=(long) (image->columns+7)/8; x < (long) bytes_per_line; x++)
1107           *q++=0x00;
1108         status=SetImageProgress(image,SaveImageTag,y,image->rows);
1109         if (status == MagickFalse)
1110           break;
1111       }
1112       break;
1113     }
1114     case 8:
1115     {
1116       /*
1117         Convert PseudoClass packet to DIB pixel.
1118       */
1119       for (y=0; y < (long) image->rows; y++)
1120       {
1121         p=GetVirtualPixels(image,0,y,image->columns,1,&image->exception);
1122         if (p == (const PixelPacket *) NULL)
1123           break;
1124         indexes=GetVirtualIndexQueue(image);
1125         q=pixels+(image->rows-y-1)*bytes_per_line;
1126         for (x=0; x < (long) image->columns; x++)
1127           *q++=(unsigned char) indexes[x];
1128         for ( ; x < (long) bytes_per_line; x++)
1129           *q++=0x00;
1130         status=SetImageProgress(image,SaveImageTag,y,image->rows);
1131         if (status == MagickFalse)
1132           break;
1133       }
1134       break;
1135     }
1136     case 16:
1137     {
1138       unsigned short
1139         word;
1140       /*
1141         Convert PseudoClass packet to DIB pixel. 
1142       */
1143       for (y=0; y < (long) image->rows; y++)
1144       {
1145         p=GetVirtualPixels(image,0,y,image->columns,1,&image->exception);
1146         if (p == (const PixelPacket *) NULL)
1147           break;
1148         q=pixels+(image->rows-y-1)*bytes_per_line;
1149         for (x=0; x < (long) image->columns; x++)
1150         {
1151           word=(unsigned short) ((ScaleColor8to5((unsigned char)
1152             ScaleQuantumToChar(GetRedPixelComponent(p))) << 11) | (ScaleColor8to6((unsigned char)
1153             ScaleQuantumToChar(GetGreenPixelComponent(p))) << 5) | (ScaleColor8to5(
1154             (unsigned char) ScaleQuantumToChar((unsigned char) GetBluePixelComponent(p)) << 0)));
1155           *q++=(unsigned char)(word & 0xff);
1156           *q++=(unsigned char)(word >> 8);
1157           p++;
1158         }
1159         for (x=2L*image->columns; x < (long) bytes_per_line; x++)
1160           *q++=0x00;
1161         status=SetImageProgress(image,SaveImageTag,y,image->rows);
1162         if (status == MagickFalse)
1163           break;
1164       }
1165       break;
1166     }
1167     case 24:
1168     case 32:
1169     {
1170       /*
1171         Convert DirectClass packet to DIB RGB pixel.
1172       */
1173       for (y=0; y < (long) image->rows; y++)
1174       {
1175         p=GetVirtualPixels(image,0,y,image->columns,1,&image->exception);
1176         if (p == (const PixelPacket *) NULL)
1177           break;
1178         q=pixels+(image->rows-y-1)*bytes_per_line;
1179         for (x=0; x < (long) image->columns; x++)
1180         {
1181           *q++=ScaleQuantumToChar(GetBluePixelComponent(p));
1182           *q++=ScaleQuantumToChar(GetGreenPixelComponent(p));
1183           *q++=ScaleQuantumToChar(GetRedPixelComponent(p));
1184           if (image->matte != MagickFalse)
1185             *q++=ScaleQuantumToChar(GetOpacityPixelComponent(p));
1186           p++;
1187         }
1188         if (dib_info.bits_per_pixel == 24)
1189           for (x=3L*image->columns; x < (long) bytes_per_line; x++)
1190             *q++=0x00;
1191         status=SetImageProgress(image,SaveImageTag,y,image->rows);
1192         if (status == MagickFalse)
1193           break;
1194       }
1195       break;
1196     }
1197   }
1198   if (dib_info.bits_per_pixel == 8)
1199     if (image_info->compression != NoCompression)
1200       {
1201         size_t
1202           length;
1203
1204         /*
1205           Convert run-length encoded raster pixels.
1206         */
1207         length=2UL*(bytes_per_line+2UL)+2UL;
1208         dib_data=(unsigned char *) AcquireQuantumMemory(length,
1209           (image->rows+2UL)*sizeof(*dib_data));
1210         if (pixels == (unsigned char *) NULL)
1211           {
1212             pixels=(unsigned char *) RelinquishMagickMemory(pixels);
1213             ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed");
1214           }
1215         dib_info.image_size=(unsigned long) EncodeImage(image,bytes_per_line,
1216           pixels,dib_data);
1217         pixels=(unsigned char *) RelinquishMagickMemory(pixels);
1218         pixels=dib_data;
1219         dib_info.compression = BI_RLE8;
1220       }
1221   /*
1222     Write DIB header.
1223   */
1224   (void) WriteBlobLSBLong(image,dib_info.size);
1225   (void) WriteBlobLSBLong(image,(unsigned long) dib_info.width);
1226   (void) WriteBlobLSBLong(image,(unsigned short) dib_info.height);
1227   (void) WriteBlobLSBShort(image,(unsigned short) dib_info.planes);
1228   (void) WriteBlobLSBShort(image,dib_info.bits_per_pixel);
1229   (void) WriteBlobLSBLong(image,dib_info.compression);
1230   (void) WriteBlobLSBLong(image,dib_info.image_size);
1231   (void) WriteBlobLSBLong(image,dib_info.x_pixels);
1232   (void) WriteBlobLSBLong(image,dib_info.y_pixels);
1233   (void) WriteBlobLSBLong(image,dib_info.number_colors);
1234   (void) WriteBlobLSBLong(image,dib_info.colors_important);
1235   if (image->storage_class == PseudoClass)
1236     {
1237       if (dib_info.bits_per_pixel <= 8)
1238         {
1239           unsigned char
1240             *dib_colormap;
1241
1242           /*
1243             Dump colormap to file.
1244           */
1245           dib_colormap=(unsigned char *) AcquireQuantumMemory((size_t)
1246             (1UL << dib_info.bits_per_pixel),4*sizeof(dib_colormap));
1247           if (dib_colormap == (unsigned char *) NULL)
1248             ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed");
1249           q=dib_colormap;
1250           for (i=0; i < (long) MagickMin(image->colors,dib_info.number_colors); i++)
1251           {
1252             *q++=ScaleQuantumToChar(image->colormap[i].blue);
1253             *q++=ScaleQuantumToChar(image->colormap[i].green);
1254             *q++=ScaleQuantumToChar(image->colormap[i].red);
1255             *q++=(Quantum) 0x0;
1256           }
1257           for ( ; i < (long) (1L << dib_info.bits_per_pixel); i++)
1258           {
1259             *q++=(Quantum) 0x0;
1260             *q++=(Quantum) 0x0;
1261             *q++=(Quantum) 0x0;
1262             *q++=(Quantum) 0x0;
1263           }
1264           (void) WriteBlob(image,(size_t) (4*(1 << dib_info.bits_per_pixel)),
1265             dib_colormap);
1266           dib_colormap=(unsigned char *) RelinquishMagickMemory(dib_colormap);
1267         }
1268       else
1269         if ((dib_info.bits_per_pixel == 16) &&
1270             (dib_info.compression == BI_BITFIELDS))
1271           {
1272             (void) WriteBlobLSBLong(image,0xf800);
1273             (void) WriteBlobLSBLong(image,0x07e0);
1274             (void) WriteBlobLSBLong(image,0x001f);
1275           }
1276     }
1277   (void) WriteBlob(image,dib_info.image_size,pixels);
1278   pixels=(unsigned char *) RelinquishMagickMemory(pixels);
1279   (void) CloseBlob(image);
1280   return(MagickTrue);
1281 }