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