]> granicus.if.org Git - imagemagick/blob - coders/bmp.c
(no commit message)
[imagemagick] / coders / bmp.c
1 /*
2 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
3 %                                                                             %
4 %                                                                             %
5 %                                                                             %
6 %                            BBBB   M   M  PPPP                               %
7 %                            B   B  MM MM  P   P                              %
8 %                            BBBB   M M M  PPPP                               %
9 %                            B   B  M   M  P                                  %
10 %                            BBBB   M   M  P                                  %
11 %                                                                             %
12 %                                                                             %
13 %             Read/Write Microsoft Windows Bitmap Image Format                %
14 %                                                                             %
15 %                              Software Design                                %
16 %                                   Cristy                                    %
17 %                            Glenn Randers-Pehrson                            %
18 %                               December 2001                                 %
19 %                                                                             %
20 %                                                                             %
21 %  Copyright 1999-2015 ImageMagick Studio LLC, a non-profit organization      %
22 %  dedicated to making software imaging solutions freely available.           %
23 %                                                                             %
24 %  You may not use this file except in compliance with the License.  You may  %
25 %  obtain a copy of the License at                                            %
26 %                                                                             %
27 %    http://www.imagemagick.org/script/license.php                            %
28 %                                                                             %
29 %  Unless required by applicable law or agreed to in writing, software        %
30 %  distributed under the License is distributed on an "AS IS" BASIS,          %
31 %  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.   %
32 %  See the License for the specific language governing permissions and        %
33 %  limitations under the License.                                             %
34 %                                                                             %
35 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
36 %
37 %
38 */
39 \f
40 /*
41   Include declarations.
42 */
43 #include "MagickCore/studio.h"
44 #include "MagickCore/blob.h"
45 #include "MagickCore/blob-private.h"
46 #include "MagickCore/cache.h"
47 #include "MagickCore/colormap-private.h"
48 #include "MagickCore/color-private.h"
49 #include "MagickCore/colormap.h"
50 #include "MagickCore/colorspace.h"
51 #include "MagickCore/colorspace-private.h"
52 #include "MagickCore/exception.h"
53 #include "MagickCore/exception-private.h"
54 #include "MagickCore/image.h"
55 #include "MagickCore/image-private.h"
56 #include "MagickCore/list.h"
57 #include "MagickCore/log.h"
58 #include "MagickCore/magick.h"
59 #include "MagickCore/memory_.h"
60 #include "MagickCore/monitor.h"
61 #include "MagickCore/monitor-private.h"
62 #include "MagickCore/option.h"
63 #include "MagickCore/pixel-accessor.h"
64 #include "MagickCore/profile.h"
65 #include "MagickCore/quantum-private.h"
66 #include "MagickCore/static.h"
67 #include "MagickCore/string_.h"
68 #include "MagickCore/module.h"
69 #include "MagickCore/transform.h"
70 \f
71 /*
72   Macro definitions (from Windows wingdi.h).
73 */
74 #undef BI_JPEG
75 #define BI_JPEG  4
76 #undef BI_PNG
77 #define BI_PNG  5
78 #if !defined(MAGICKCORE_WINDOWS_SUPPORT) || defined(__MINGW32__) || defined(__MINGW64__)
79 #undef BI_RGB
80 #define BI_RGB  0
81 #undef BI_RLE8
82 #define BI_RLE8  1
83 #undef BI_RLE4
84 #define BI_RLE4  2
85 #undef BI_BITFIELDS
86 #define BI_BITFIELDS  3
87
88 #undef LCS_CALIBRATED_RBG
89 #define LCS_CALIBRATED_RBG  0
90 #undef LCS_sRGB
91 #define LCS_sRGB  1
92 #undef LCS_WINDOWS_COLOR_SPACE
93 #define LCS_WINDOWS_COLOR_SPACE  2
94 #undef PROFILE_LINKED
95 #define PROFILE_LINKED  3
96 #undef PROFILE_EMBEDDED
97 #define PROFILE_EMBEDDED  4
98
99 #undef LCS_GM_BUSINESS
100 #define LCS_GM_BUSINESS  1  /* Saturation */
101 #undef LCS_GM_GRAPHICS
102 #define LCS_GM_GRAPHICS  2  /* Relative */
103 #undef LCS_GM_IMAGES
104 #define LCS_GM_IMAGES  4  /* Perceptual */
105 #undef LCS_GM_ABS_COLORIMETRIC
106 #define LCS_GM_ABS_COLORIMETRIC  8  /* Absolute */
107 #endif
108 \f
109 /*
110   Typedef declarations.
111 */
112 typedef struct _BMPInfo
113 {
114   unsigned int
115     file_size,
116     ba_offset,
117     offset_bits,
118     size;
119
120   ssize_t
121     width,
122     height;
123
124   unsigned short
125     planes,
126     bits_per_pixel;
127
128   unsigned int
129     compression,
130     image_size,
131     x_pixels,
132     y_pixels,
133     number_colors,
134     red_mask,
135     green_mask,
136     blue_mask,
137     alpha_mask,
138     colors_important;
139
140   int
141     colorspace;
142
143   PrimaryInfo
144     red_primary,
145     green_primary,
146     blue_primary,
147     gamma_scale;
148 } BMPInfo;
149 \f
150 /*
151   Forward declarations.
152 */
153 static MagickBooleanType
154   WriteBMPImage(const ImageInfo *,Image *,ExceptionInfo *);
155 \f
156 /*
157 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
158 %                                                                             %
159 %                                                                             %
160 %                                                                             %
161 %   D e c o d e I m a g e                                                     %
162 %                                                                             %
163 %                                                                             %
164 %                                                                             %
165 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
166 %
167 %  DecodeImage unpacks the packed image pixels into runlength-encoded
168 %  pixel packets.
169 %
170 %  The format of the DecodeImage method is:
171 %
172 %      MagickBooleanType DecodeImage(Image *image,
173 %        const size_t compression,unsigned char *pixels)
174 %
175 %  A description of each parameter follows:
176 %
177 %    o image: the address of a structure of type Image.
178 %
179 %    o compression:  Zero means uncompressed.  A value of 1 means the
180 %      compressed pixels are runlength encoded for a 256-color bitmap.
181 %      A value of 2 means a 16-color bitmap.  A value of 3 means bitfields
182 %      encoding.
183 %
184 %    o pixels:  The address of a byte (8 bits) array of pixel data created by
185 %      the decoding process.
186 %
187 */
188
189 static inline ssize_t MagickAbsoluteValue(const ssize_t x)
190 {
191   if (x < 0)
192     return(-x);
193   return(x);
194 }
195
196 static inline size_t MagickMax(const size_t x,const size_t y)
197 {
198   if (x > y)
199     return(x);
200   return(y);
201 }
202
203 static inline ssize_t MagickMin(const ssize_t x,const ssize_t y)
204 {
205   if (x < y)
206     return(x);
207   return(y);
208 }
209
210 static MagickBooleanType DecodeImage(Image *image,const size_t compression,
211   unsigned char *pixels)
212 {
213   int
214     count;
215
216   register ssize_t
217     i,
218     x;
219
220   register unsigned char
221     *p,
222     *q;
223
224   ssize_t
225     y;
226
227   unsigned char
228     byte;
229
230   assert(image != (Image *) NULL);
231   assert(image->signature == MagickSignature);
232   if (image->debug != MagickFalse)
233     (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
234   assert(pixels != (unsigned char *) NULL);
235   (void) ResetMagickMemory(pixels,0,(size_t) image->columns*image->rows*
236     sizeof(*pixels));
237   byte=0;
238   x=0;
239   p=pixels;
240   q=pixels+(size_t) image->columns*image->rows;
241   for (y=0; y < (ssize_t) image->rows; )
242   {
243     if ((p < pixels) || (p >= q))
244       break;
245     count=ReadBlobByte(image);
246     if (count == EOF)
247       break;
248     if (count != 0)
249       {
250         /*
251           Encoded mode.
252         */
253         count=(int) MagickMin((ssize_t) count,(ssize_t) (q-p));
254         byte=(unsigned char) ReadBlobByte(image);
255         if (compression == BI_RLE8)
256           {
257             for (i=0; i < (ssize_t) count; i++)
258               *p++=(unsigned char) byte;
259           }
260         else
261           {
262             for (i=0; i < (ssize_t) count; i++)
263               *p++=(unsigned char)
264                 ((i & 0x01) != 0 ? (byte & 0x0f) : ((byte >> 4) & 0x0f));
265           }
266         x+=count;
267       }
268     else
269       {
270         /*
271           Escape mode.
272         */
273         count=ReadBlobByte(image);
274         if (count == 0x01)
275           return(MagickTrue);
276         switch (count)
277         {
278           case 0x00:
279           {
280             /*
281               End of line.
282             */
283             x=0;
284             y++;
285             p=pixels+y*image->columns;
286             break;
287           }
288           case 0x02:
289           {
290             /*
291               Delta mode.
292             */
293             x+=ReadBlobByte(image);
294             y+=ReadBlobByte(image);
295             p=pixels+y*image->columns+x;
296             break;
297           }
298           default:
299           {
300             /*
301               Absolute mode.
302             */
303             count=(int) MagickMin((ssize_t) count,(ssize_t) (q-p));
304             if (compression == BI_RLE8)
305               for (i=0; i < (ssize_t) count; i++)
306                 *p++=(unsigned char) ReadBlobByte(image);
307             else
308               for (i=0; i < (ssize_t) count; i++)
309               {
310                 if ((i & 0x01) == 0)
311                   byte=(unsigned char) ReadBlobByte(image);
312                 *p++=(unsigned char)
313                   ((i & 0x01) != 0 ? (byte & 0x0f) : ((byte >> 4) & 0x0f));
314               }
315             x+=count;
316             /*
317               Read pad byte.
318             */
319             if (compression == BI_RLE8)
320               {
321                 if ((count & 0x01) != 0)
322                   (void) ReadBlobByte(image);
323               }
324             else
325               if (((count & 0x03) == 1) || ((count & 0x03) == 2))
326                 (void) ReadBlobByte(image);
327             break;
328           }
329         }
330       }
331     if (SetImageProgress(image,LoadImageTag,(MagickOffsetType) y,image->rows) == MagickFalse)
332       break;
333   }
334   (void) ReadBlobByte(image);  /* end of line */
335   (void) ReadBlobByte(image);
336   return(MagickTrue);
337 }
338 \f
339 /*
340 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
341 %                                                                             %
342 %                                                                             %
343 %                                                                             %
344 %   E n c o d e I m a g e                                                     %
345 %                                                                             %
346 %                                                                             %
347 %                                                                             %
348 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
349 %
350 %  EncodeImage compresses pixels using a runlength encoded format.
351 %
352 %  The format of the EncodeImage method is:
353 %
354 %    static MagickBooleanType EncodeImage(Image *image,
355 %      const size_t bytes_per_line,const unsigned char *pixels,
356 %      unsigned char *compressed_pixels)
357 %
358 %  A description of each parameter follows:
359 %
360 %    o image:  The image.
361 %
362 %    o bytes_per_line: the number of bytes in a scanline of compressed pixels
363 %
364 %    o pixels:  The address of a byte (8 bits) array of pixel data created by
365 %      the compression process.
366 %
367 %    o compressed_pixels:  The address of a byte (8 bits) array of compressed
368 %      pixel data.
369 %
370 */
371 static size_t EncodeImage(Image *image,const size_t bytes_per_line,
372   const unsigned char *pixels,unsigned char *compressed_pixels)
373 {
374   MagickBooleanType
375     status;
376
377   register const unsigned char
378     *p;
379
380   register ssize_t
381     i,
382     x;
383
384   register unsigned char
385     *q;
386
387   ssize_t
388     y;
389
390   /*
391     Runlength encode pixels.
392   */
393   assert(image != (Image *) NULL);
394   assert(image->signature == MagickSignature);
395   if (image->debug != MagickFalse)
396     (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
397   assert(pixels != (const unsigned char *) NULL);
398   assert(compressed_pixels != (unsigned char *) NULL);
399   p=pixels;
400   q=compressed_pixels;
401   i=0;
402   for (y=0; y < (ssize_t) image->rows; y++)
403   {
404     for (x=0; x < (ssize_t) bytes_per_line; x+=i)
405     {
406       /*
407         Determine runlength.
408       */
409       for (i=1; ((x+i) < (ssize_t) bytes_per_line); i++)
410         if ((i == 255) || (*(p+i) != *p))
411           break;
412       *q++=(unsigned char) i;
413       *q++=(*p);
414       p+=i;
415     }
416     /*
417       End of line.
418     */
419     *q++=(unsigned char) 0x00;
420     *q++=(unsigned char) 0x00;
421     status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y,
422       image->rows);
423     if (status == MagickFalse)
424       break;
425   }
426   /*
427     End of bitmap.
428   */
429   *q++=(unsigned char) 0x00;
430   *q++=(unsigned char) 0x01;
431   return((size_t) (q-compressed_pixels));
432 }
433 \f
434 /*
435 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
436 %                                                                             %
437 %                                                                             %
438 %                                                                             %
439 %   I s B M P                                                                 %
440 %                                                                             %
441 %                                                                             %
442 %                                                                             %
443 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
444 %
445 %  IsBMP() returns MagickTrue if the image format type, identified by the
446 %  magick string, is BMP.
447 %
448 %  The format of the IsBMP method is:
449 %
450 %      MagickBooleanType IsBMP(const unsigned char *magick,const size_t length)
451 %
452 %  A description of each parameter follows:
453 %
454 %    o magick: compare image format pattern against these bytes.
455 %
456 %    o length: Specifies the length of the magick string.
457 %
458 */
459 static MagickBooleanType IsBMP(const unsigned char *magick,const size_t length)
460 {
461   if (length < 2)
462     return(MagickFalse);
463   if ((LocaleNCompare((char *) magick,"BA",2) == 0) ||
464       (LocaleNCompare((char *) magick,"BM",2) == 0) ||
465       (LocaleNCompare((char *) magick,"IC",2) == 0) ||
466       (LocaleNCompare((char *) magick,"PI",2) == 0) ||
467       (LocaleNCompare((char *) magick,"CI",2) == 0) ||
468       (LocaleNCompare((char *) magick,"CP",2) == 0))
469     return(MagickTrue);
470   return(MagickFalse);
471 }
472 \f
473 /*
474 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
475 %                                                                             %
476 %                                                                             %
477 %                                                                             %
478 %   R e a d B M P I m a g e                                                   %
479 %                                                                             %
480 %                                                                             %
481 %                                                                             %
482 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
483 %
484 %  ReadBMPImage() reads a Microsoft Windows bitmap image file, Version
485 %  2, 3 (for Windows or NT), or 4, and  returns it.  It allocates the memory
486 %  necessary for the new Image structure and returns a pointer to the new
487 %  image.
488 %
489 %  The format of the ReadBMPImage method is:
490 %
491 %      image=ReadBMPImage(image_info)
492 %
493 %  A description of each parameter follows:
494 %
495 %    o image_info: the image info.
496 %
497 %    o exception: return any errors or warnings in this structure.
498 %
499 */
500
501 static Image *ReadBMPImage(const ImageInfo *image_info,ExceptionInfo *exception)
502 {
503   BMPInfo
504     bmp_info;
505
506   Image
507     *image;
508
509   MagickBooleanType
510     status;
511
512   MagickOffsetType
513     offset,
514     start_position;
515
516   MemoryInfo
517     *pixel_info;
518
519   Quantum
520     index;
521
522   register Quantum
523     *q;
524
525   register ssize_t
526     i,
527     x;
528
529   register unsigned char
530     *p;
531
532   size_t
533     bit,
534     blue,
535     bytes_per_line,
536     green,
537     length,
538     red;
539
540   ssize_t
541     count,
542     y;
543
544   unsigned char
545     magick[12],
546     *pixels;
547
548   /*
549     Open image file.
550   */
551   assert(image_info != (const ImageInfo *) NULL);
552   assert(image_info->signature == MagickSignature);
553   if (image_info->debug != MagickFalse)
554     (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",
555       image_info->filename);
556   assert(exception != (ExceptionInfo *) NULL);
557   assert(exception->signature == MagickSignature);
558   image=AcquireImage(image_info,exception);
559   status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception);
560   if (status == MagickFalse)
561     {
562       image=DestroyImageList(image);
563       return((Image *) NULL);
564     }
565   /*
566     Determine if this a BMP file.
567   */
568   (void) ResetMagickMemory(&bmp_info,0,sizeof(bmp_info));
569   bmp_info.ba_offset=0;
570   start_position=0;
571   count=ReadBlob(image,2,magick);
572   do
573   {
574     PixelInfo
575       quantum_bits;
576
577     PixelPacket
578       shift;
579
580     size_t
581       profile_data,
582       profile_size;
583
584     /*
585       Verify BMP identifier.
586     */
587     if (bmp_info.ba_offset == 0)
588       start_position=TellBlob(image)-2;
589     bmp_info.ba_offset=0;
590     while (LocaleNCompare((char *) magick,"BA",2) == 0)
591     {
592       bmp_info.file_size=ReadBlobLSBLong(image);
593       bmp_info.ba_offset=ReadBlobLSBLong(image);
594       bmp_info.offset_bits=ReadBlobLSBLong(image);
595       count=ReadBlob(image,2,magick);
596       if (count != 2)
597         break;
598     }
599     if (image->debug != MagickFalse)
600       (void) LogMagickEvent(CoderEvent,GetMagickModule(),"  Magick: %c%c",
601         magick[0],magick[1]);
602     if ((count == 0) || ((LocaleNCompare((char *) magick,"BM",2) != 0) &&
603         (LocaleNCompare((char *) magick,"CI",2) != 0)))
604       ThrowReaderException(CorruptImageError,"ImproperImageHeader");
605     bmp_info.file_size=ReadBlobLSBLong(image);
606     (void) ReadBlobLSBLong(image);
607     bmp_info.offset_bits=ReadBlobLSBLong(image);
608     bmp_info.size=ReadBlobLSBLong(image);
609     if (image->debug != MagickFalse)
610       (void) LogMagickEvent(CoderEvent,GetMagickModule(),"  BMP size: %u",
611         bmp_info.size);
612     if (bmp_info.size == 12)
613       {
614         /*
615           OS/2 BMP image file.
616         */
617         (void) CopyMagickString(image->magick,"BMP2",MaxTextExtent);
618         bmp_info.width=(ssize_t) ((short) ReadBlobLSBShort(image));
619         bmp_info.height=(ssize_t) ((short) ReadBlobLSBShort(image));
620         bmp_info.planes=ReadBlobLSBShort(image);
621         bmp_info.bits_per_pixel=ReadBlobLSBShort(image);
622         bmp_info.x_pixels=0;
623         bmp_info.y_pixels=0;
624         bmp_info.number_colors=0;
625         bmp_info.compression=BI_RGB;
626         bmp_info.image_size=0;
627         bmp_info.alpha_mask=0;
628         if (image->debug != MagickFalse)
629           {
630             (void) LogMagickEvent(CoderEvent,GetMagickModule(),
631               "  Format: OS/2 Bitmap");
632             (void) LogMagickEvent(CoderEvent,GetMagickModule(),
633               "  Geometry: %.20gx%.20g",(double) bmp_info.width,(double)
634               bmp_info.height);
635           }
636       }
637     else
638       {
639         /*
640           Microsoft Windows BMP image file.
641         */
642         if (bmp_info.size < 40)
643           ThrowReaderException(CorruptImageError,"NonOS2HeaderSizeError");
644         bmp_info.width=(ssize_t) ((int) ReadBlobLSBLong(image));
645         bmp_info.height=(ssize_t) ((int) ReadBlobLSBLong(image));
646         bmp_info.planes=ReadBlobLSBShort(image);
647         bmp_info.bits_per_pixel=ReadBlobLSBShort(image);
648         bmp_info.compression=ReadBlobLSBLong(image);
649         bmp_info.image_size=ReadBlobLSBLong(image);
650         bmp_info.x_pixels=ReadBlobLSBLong(image);
651         bmp_info.y_pixels=ReadBlobLSBLong(image);
652         bmp_info.number_colors=ReadBlobLSBLong(image);
653         bmp_info.colors_important=ReadBlobLSBLong(image);
654         profile_data=0;
655         profile_size=0;
656         if (image->debug != MagickFalse)
657           {
658             (void) LogMagickEvent(CoderEvent,GetMagickModule(),
659               "  Format: MS Windows bitmap");
660             (void) LogMagickEvent(CoderEvent,GetMagickModule(),
661               "  Geometry: %.20gx%.20g",(double) bmp_info.width,(double)
662               bmp_info.height);
663             (void) LogMagickEvent(CoderEvent,GetMagickModule(),
664               "  Bits per pixel: %.20g",(double) bmp_info.bits_per_pixel);
665             switch ((int) bmp_info.compression)
666             {
667               case BI_RGB:
668               {
669                 (void) LogMagickEvent(CoderEvent,GetMagickModule(),
670                   "  Compression: BI_RGB");
671                 break;
672               }
673               case BI_RLE4:
674               {
675                 (void) LogMagickEvent(CoderEvent,GetMagickModule(),
676                   "  Compression: BI_RLE4");
677                 break;
678               }
679               case BI_RLE8:
680               {
681                 (void) LogMagickEvent(CoderEvent,GetMagickModule(),
682                   "  Compression: BI_RLE8");
683                 break;
684               }
685               case BI_BITFIELDS:
686               {
687                 (void) LogMagickEvent(CoderEvent,GetMagickModule(),
688                   "  Compression: BI_BITFIELDS");
689                 break;
690               }
691               case BI_PNG:
692               {
693                 (void) LogMagickEvent(CoderEvent,GetMagickModule(),
694                   "  Compression: BI_PNG");
695                 break;
696               }
697               case BI_JPEG:
698               {
699                 (void) LogMagickEvent(CoderEvent,GetMagickModule(),
700                   "  Compression: BI_JPEG");
701                 break;
702               }
703               default:
704               {
705                 (void) LogMagickEvent(CoderEvent,GetMagickModule(),
706                   "  Compression: UNKNOWN (%u)",bmp_info.compression);
707               }
708             }
709             (void) LogMagickEvent(CoderEvent,GetMagickModule(),
710               "  Number of colors: %u",bmp_info.number_colors);
711           }
712         bmp_info.red_mask=ReadBlobLSBLong(image);
713         bmp_info.green_mask=ReadBlobLSBLong(image);
714         bmp_info.blue_mask=ReadBlobLSBLong(image);
715         if (bmp_info.size > 40)
716           {
717
718             double
719               sum;
720
721             /*
722               Read color management information.
723             */
724             bmp_info.alpha_mask=ReadBlobLSBLong(image);
725             bmp_info.colorspace=(int) ReadBlobLSBLong(image);
726             /*
727               Decode 2^30 fixed point formatted CIE primaries.
728             */
729 #           define BMP_DENOM ((double) 0x40000000)
730             bmp_info.red_primary.x=(double) ReadBlobLSBLong(image)/BMP_DENOM;
731             bmp_info.red_primary.y=(double) ReadBlobLSBLong(image)/BMP_DENOM;
732             bmp_info.red_primary.z=(double) ReadBlobLSBLong(image)/BMP_DENOM;
733             bmp_info.green_primary.x=(double) ReadBlobLSBLong(image)/BMP_DENOM;
734             bmp_info.green_primary.y=(double) ReadBlobLSBLong(image)/BMP_DENOM;
735             bmp_info.green_primary.z=(double) ReadBlobLSBLong(image)/BMP_DENOM;
736             bmp_info.blue_primary.x=(double) ReadBlobLSBLong(image)/BMP_DENOM;
737             bmp_info.blue_primary.y=(double) ReadBlobLSBLong(image)/BMP_DENOM;
738             bmp_info.blue_primary.z=(double) ReadBlobLSBLong(image)/BMP_DENOM;
739
740             sum=bmp_info.red_primary.x+bmp_info.red_primary.y+
741               bmp_info.red_primary.z;
742             bmp_info.red_primary.x/=sum;
743             bmp_info.red_primary.y/=sum;
744             image->chromaticity.red_primary.x=bmp_info.red_primary.x;
745             image->chromaticity.red_primary.y=bmp_info.red_primary.y;
746
747             sum=bmp_info.green_primary.x+bmp_info.green_primary.y+
748               bmp_info.green_primary.z;
749             bmp_info.green_primary.x/=sum;
750             bmp_info.green_primary.y/=sum;
751             image->chromaticity.green_primary.x=bmp_info.green_primary.x;
752             image->chromaticity.green_primary.y=bmp_info.green_primary.y;
753
754             sum=bmp_info.blue_primary.x+bmp_info.blue_primary.y+
755               bmp_info.blue_primary.z;
756             bmp_info.blue_primary.x/=sum;
757             bmp_info.blue_primary.y/=sum;
758             image->chromaticity.blue_primary.x=bmp_info.blue_primary.x;
759             image->chromaticity.blue_primary.y=bmp_info.blue_primary.y;
760
761             /*
762               Decode 16^16 fixed point formatted gamma_scales.
763             */
764             bmp_info.gamma_scale.x=(double) ReadBlobLSBLong(image)/0x10000;
765             bmp_info.gamma_scale.y=(double) ReadBlobLSBLong(image)/0x10000;
766             bmp_info.gamma_scale.z=(double) ReadBlobLSBLong(image)/0x10000;
767             /*
768               Compute a single gamma from the BMP 3-channel gamma.
769             */
770             image->gamma=(bmp_info.gamma_scale.x+bmp_info.gamma_scale.y+
771               bmp_info.gamma_scale.z)/3.0;
772           }
773         else
774           (void) CopyMagickString(image->magick,"BMP3",MaxTextExtent);
775
776         if (bmp_info.size > 108)
777           {
778             size_t
779               intent;
780
781             /*
782               Read BMP Version 5 color management information.
783             */
784             intent=ReadBlobLSBLong(image);
785             switch ((int) intent)
786             {
787               case LCS_GM_BUSINESS:
788               {
789                 image->rendering_intent=SaturationIntent;
790                 break;
791               }
792               case LCS_GM_GRAPHICS:
793               {
794                 image->rendering_intent=RelativeIntent;
795                 break;
796               }
797               case LCS_GM_IMAGES:
798               {
799                 image->rendering_intent=PerceptualIntent;
800                 break;
801               }
802               case LCS_GM_ABS_COLORIMETRIC:
803               {
804                 image->rendering_intent=AbsoluteIntent;
805                 break;
806               }
807             }
808             profile_data=ReadBlobLSBLong(image);
809             profile_size=ReadBlobLSBLong(image);
810             (void) profile_data;
811             (void) profile_size;
812             (void) ReadBlobLSBLong(image);  /* Reserved byte */
813           }
814       }
815     if ((MagickSizeType) bmp_info.file_size > GetBlobSize(image))
816       (void) ThrowMagickException(exception,GetMagickModule(),CorruptImageError,
817         "LengthAndFilesizeDoNotMatch","`%s'",image->filename);
818     else
819       if ((MagickSizeType) bmp_info.file_size < GetBlobSize(image))
820         (void) ThrowMagickException(exception,GetMagickModule(),
821           CorruptImageWarning,"LengthAndFilesizeDoNotMatch","`%s'",
822           image->filename);
823     if (bmp_info.width <= 0)
824       ThrowReaderException(CorruptImageError,"NegativeOrZeroImageSize");
825     if (bmp_info.height == 0)
826       ThrowReaderException(CorruptImageError,"NegativeOrZeroImageSize");
827     if (bmp_info.planes != 1)
828       ThrowReaderException(CorruptImageError,"StaticPlanesValueNotEqualToOne");
829     if ((bmp_info.bits_per_pixel != 1) && (bmp_info.bits_per_pixel != 4) &&
830         (bmp_info.bits_per_pixel != 8) && (bmp_info.bits_per_pixel != 16) &&
831         (bmp_info.bits_per_pixel != 24) && (bmp_info.bits_per_pixel != 32))
832       ThrowReaderException(CorruptImageError,"UnrecognizedBitsPerPixel");
833     if (bmp_info.bits_per_pixel < 16 &&
834         bmp_info.number_colors > (1U << bmp_info.bits_per_pixel))
835       {
836         ThrowReaderException(CorruptImageError,
837             "UnrecognizedNumberOfColors");
838       }
839     if ((bmp_info.compression == 1) && (bmp_info.bits_per_pixel != 8))
840       ThrowReaderException(CorruptImageError,"UnrecognizedBitsPerPixel");
841     if ((bmp_info.compression == 2) && (bmp_info.bits_per_pixel != 4))
842       ThrowReaderException(CorruptImageError,"UnrecognizedBitsPerPixel");
843     if ((bmp_info.compression == 3) && (bmp_info.bits_per_pixel < 16))
844       ThrowReaderException(CorruptImageError,"UnrecognizedBitsPerPixel");
845     switch (bmp_info.compression)
846     {
847       case BI_RGB:
848       case BI_RLE8:
849       case BI_RLE4:
850       case BI_BITFIELDS:
851         break;
852       case BI_JPEG:
853         ThrowReaderException(CoderError,"JPEGCompressNotSupported");
854       case BI_PNG:
855         ThrowReaderException(CoderError,"PNGCompressNotSupported");
856       default:
857         ThrowReaderException(CorruptImageError,"UnrecognizedImageCompression");
858     }
859     image->columns=(size_t) MagickAbsoluteValue(bmp_info.width);
860     image->rows=(size_t) MagickAbsoluteValue(bmp_info.height);
861     image->depth=bmp_info.bits_per_pixel <= 8 ? bmp_info.bits_per_pixel : 8;
862     image->alpha_trait=((bmp_info.alpha_mask != 0) &&
863       (bmp_info.compression == BI_BITFIELDS)) ||
864       (bmp_info.bits_per_pixel == 32) ? BlendPixelTrait : UndefinedPixelTrait;
865     if (bmp_info.bits_per_pixel < 16)
866       {
867         size_t
868           one;
869
870         image->storage_class=PseudoClass;
871         image->colors=bmp_info.number_colors;
872         one=1;
873         if (image->colors == 0)
874           image->colors=one << bmp_info.bits_per_pixel;
875       }
876     if (image->storage_class == PseudoClass)
877       {
878         unsigned char
879           *bmp_colormap;
880
881         size_t
882           packet_size;
883
884         /*
885           Read BMP raster colormap.
886         */
887         if (image->debug != MagickFalse)
888           (void) LogMagickEvent(CoderEvent,GetMagickModule(),
889             "  Reading colormap of %.20g colors",(double) image->colors);
890         if (AcquireImageColormap(image,image->colors,exception) == MagickFalse)
891           ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
892         bmp_colormap=(unsigned char *) AcquireQuantumMemory((size_t)
893           image->colors,4*sizeof(*bmp_colormap));
894         if (bmp_colormap == (unsigned char *) NULL)
895           ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
896         if ((bmp_info.size == 12) || (bmp_info.size == 64))
897           packet_size=3;
898         else
899           packet_size=4;
900         offset=SeekBlob(image,start_position+14+bmp_info.size,SEEK_SET);
901         if (offset < 0)
902           ThrowReaderException(CorruptImageError,"ImproperImageHeader");
903         count=ReadBlob(image,packet_size*image->colors,bmp_colormap);
904         if (count != (ssize_t) (packet_size*image->colors))
905           ThrowReaderException(CorruptImageError,"InsufficientImageDataInFile");
906         p=bmp_colormap;
907         for (i=0; i < (ssize_t) image->colors; i++)
908         {
909           image->colormap[i].blue=(MagickRealType) ScaleCharToQuantum(*p++);
910           image->colormap[i].green=(MagickRealType) ScaleCharToQuantum(*p++);
911           image->colormap[i].red=(MagickRealType) ScaleCharToQuantum(*p++);
912           if (packet_size == 4)
913             p++;
914         }
915         bmp_colormap=(unsigned char *) RelinquishMagickMemory(bmp_colormap);
916       }
917     image->resolution.x=(double) bmp_info.x_pixels/100.0;
918     image->resolution.y=(double) bmp_info.y_pixels/100.0;
919     image->units=PixelsPerCentimeterResolution;
920     if ((image_info->ping != MagickFalse) && (image_info->number_scenes != 0))
921       if (image->scene >= (image_info->scene+image_info->number_scenes-1))
922         break;
923     /*
924       Read image data.
925     */
926     offset=SeekBlob(image,start_position+bmp_info.offset_bits,SEEK_SET);
927     if (offset < 0)
928       ThrowReaderException(CorruptImageError,"ImproperImageHeader");
929     if (bmp_info.compression == BI_RLE4)
930       bmp_info.bits_per_pixel<<=1;
931     bytes_per_line=4*((image->columns*bmp_info.bits_per_pixel+31)/32);
932     length=(size_t) bytes_per_line*image->rows;
933     pixel_info=AcquireVirtualMemory((size_t) image->rows,
934       MagickMax(bytes_per_line,image->columns+256UL)*sizeof(*pixels));
935     if (pixel_info == (MemoryInfo *) NULL)
936       ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
937     pixels=(unsigned char *) GetVirtualMemoryBlob(pixel_info);
938     if ((bmp_info.compression == BI_RGB) ||
939         (bmp_info.compression == BI_BITFIELDS))
940       {
941         if (image->debug != MagickFalse)
942           (void) LogMagickEvent(CoderEvent,GetMagickModule(),
943             "  Reading pixels (%.20g bytes)",(double) length);
944         count=ReadBlob(image,length,pixels);
945         if (count != (ssize_t) length)
946           {
947             pixel_info=RelinquishVirtualMemory(pixel_info);
948             ThrowReaderException(CorruptImageError,
949               "InsufficientImageDataInFile");
950           }
951       }
952     else
953       {
954         /*
955           Convert run-length encoded raster pixels.
956         */
957         status=DecodeImage(image,bmp_info.compression,pixels);
958         if (status == MagickFalse)
959           {
960             pixel_info=RelinquishVirtualMemory(pixel_info);
961             ThrowReaderException(CorruptImageError,
962               "UnableToRunlengthDecodeImage");
963           }
964       }
965     /*
966       Convert BMP raster image to pixel packets.
967     */
968     if (bmp_info.compression == BI_RGB)
969       {
970         bmp_info.alpha_mask=image->alpha_trait == BlendPixelTrait ?
971           0xff000000U : 0U;
972         bmp_info.red_mask=0x00ff0000U;
973         bmp_info.green_mask=0x0000ff00U;
974         bmp_info.blue_mask=0x000000ffU;
975         if (bmp_info.bits_per_pixel == 16)
976           {
977             /*
978               RGB555.
979             */
980             bmp_info.red_mask=0x00007c00U;
981             bmp_info.green_mask=0x000003e0U;
982             bmp_info.blue_mask=0x0000001fU;
983           }
984       }
985     if ((bmp_info.bits_per_pixel == 16) || (bmp_info.bits_per_pixel == 32))
986       {
987         register size_t
988           sample;
989
990         /*
991           Get shift and quantum bits info from bitfield masks.
992         */
993         (void) ResetMagickMemory(&shift,0,sizeof(shift));
994         (void) ResetMagickMemory(&quantum_bits,0,sizeof(quantum_bits));
995         if (bmp_info.red_mask != 0)
996           while (((bmp_info.red_mask << shift.red) & 0x80000000UL) == 0)
997             shift.red++;
998         if (bmp_info.green_mask != 0)
999           while (((bmp_info.green_mask << shift.green) & 0x80000000UL) == 0)
1000             shift.green++;
1001         if (bmp_info.blue_mask != 0)
1002           while (((bmp_info.blue_mask << shift.blue) & 0x80000000UL) == 0)
1003             shift.blue++;
1004         if (bmp_info.alpha_mask != 0)
1005           while (((bmp_info.alpha_mask << shift.alpha) & 0x80000000UL) == 0)
1006             shift.alpha++;
1007         sample=shift.red;
1008         while (((bmp_info.red_mask << sample) & 0x80000000UL) != 0)
1009           sample++;
1010         quantum_bits.red=(MagickRealType) (sample-shift.red);
1011         sample=shift.green;
1012         while (((bmp_info.green_mask << sample) & 0x80000000UL) != 0)
1013           sample++;
1014         quantum_bits.green=(MagickRealType) (sample-shift.green);
1015         sample=shift.blue;
1016         while (((bmp_info.blue_mask << sample) & 0x80000000UL) != 0)
1017           sample++;
1018         quantum_bits.blue=(MagickRealType) (sample-shift.blue);
1019         sample=shift.alpha;
1020         while (((bmp_info.alpha_mask << sample) & 0x80000000UL) != 0)
1021           sample++;
1022         quantum_bits.alpha=(MagickRealType) (sample-shift.alpha);
1023       }
1024     switch (bmp_info.bits_per_pixel)
1025     {
1026       case 1:
1027       {
1028         /*
1029           Convert bitmap scanline.
1030         */
1031         for (y=(ssize_t) image->rows-1; y >= 0; y--)
1032         {
1033           p=pixels+(image->rows-y-1)*bytes_per_line;
1034           q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);
1035           if (q == (Quantum *) NULL)
1036             break;
1037           for (x=0; x < ((ssize_t) image->columns-7); x+=8)
1038           {
1039             for (bit=0; bit < 8; bit++)
1040             {
1041               index=(Quantum) (((*p) & (0x80 >> bit)) != 0 ? 0x01 : 0x00);
1042               SetPixelIndex(image,index,q);
1043               q+=GetPixelChannels(image);
1044             }
1045             p++;
1046           }
1047           if ((image->columns % 8) != 0)
1048             {
1049               for (bit=0; bit < (image->columns % 8); bit++)
1050               {
1051                 index=(Quantum) (((*p) & (0x80 >> bit)) != 0 ? 0x01 : 0x00);
1052                 SetPixelIndex(image,index,q);
1053                 q+=GetPixelChannels(image);
1054               }
1055               p++;
1056             }
1057           if (SyncAuthenticPixels(image,exception) == MagickFalse)
1058             break;
1059           if (image->previous == (Image *) NULL)
1060             {
1061               status=SetImageProgress(image,LoadImageTag,(MagickOffsetType)
1062                 (image->rows-y),image->rows);
1063               if (status == MagickFalse)
1064                 break;
1065             }
1066         }
1067         (void) SyncImage(image,exception);
1068         break;
1069       }
1070       case 4:
1071       {
1072         /*
1073           Convert PseudoColor scanline.
1074         */
1075         for (y=(ssize_t) image->rows-1; y >= 0; y--)
1076         {
1077           p=pixels+(image->rows-y-1)*bytes_per_line;
1078           q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);
1079           if (q == (Quantum *) NULL)
1080             break;
1081           for (x=0; x < ((ssize_t) image->columns-1); x+=2)
1082           {
1083             index=ConstrainColormapIndex(image,(*p >> 4) & 0x0f,exception);
1084             SetPixelIndex(image,index,q);
1085             q+=GetPixelChannels(image);
1086             index=ConstrainColormapIndex(image,*p & 0x0f,exception);
1087             SetPixelIndex(image,index,q);
1088             q+=GetPixelChannels(image);
1089             p++;
1090           }
1091           if ((image->columns % 2) != 0)
1092             {
1093               index=ConstrainColormapIndex(image,(*p >> 4) & 0xf,exception);
1094               SetPixelIndex(image,index,q);
1095               q+=GetPixelChannels(image);
1096               p++;
1097             }
1098           if (SyncAuthenticPixels(image,exception) == MagickFalse)
1099             break;
1100           if (image->previous == (Image *) NULL)
1101             {
1102               status=SetImageProgress(image,LoadImageTag,(MagickOffsetType)
1103                 (image->rows-y),image->rows);
1104               if (status == MagickFalse)
1105                 break;
1106             }
1107         }
1108         (void) SyncImage(image,exception);
1109         break;
1110       }
1111       case 8:
1112       {
1113         /*
1114           Convert PseudoColor scanline.
1115         */
1116         if ((bmp_info.compression == BI_RLE8) ||
1117             (bmp_info.compression == BI_RLE4))
1118           bytes_per_line=image->columns;
1119         for (y=(ssize_t) image->rows-1; y >= 0; y--)
1120         {
1121           p=pixels+(image->rows-y-1)*bytes_per_line;
1122           q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);
1123           if (q == (Quantum *) NULL)
1124             break;
1125           for (x=(ssize_t) image->columns; x != 0; --x)
1126           {
1127             index=ConstrainColormapIndex(image,*p++,exception);
1128             SetPixelIndex(image,index,q);
1129             q+=GetPixelChannels(image);
1130           }
1131           if (SyncAuthenticPixels(image,exception) == MagickFalse)
1132             break;
1133           offset=(MagickOffsetType) (image->rows-y-1);
1134           if (image->previous == (Image *) NULL)
1135             {
1136               status=SetImageProgress(image,LoadImageTag,(MagickOffsetType)
1137                 (image->rows-y),image->rows);
1138               if (status == MagickFalse)
1139                 break;
1140             }
1141         }
1142         (void) SyncImage(image,exception);
1143         break;
1144       }
1145       case 16:
1146       {
1147         size_t
1148           alpha,
1149           pixel;
1150
1151         /*
1152           Convert bitfield encoded 16-bit PseudoColor scanline.
1153         */
1154         if (bmp_info.compression != BI_RGB &&
1155             bmp_info.compression != BI_BITFIELDS)
1156           {
1157             pixel_info=RelinquishVirtualMemory(pixel_info);
1158             ThrowReaderException(CorruptImageError,
1159               "UnrecognizedImageCompression");
1160           }
1161         bytes_per_line=2*(image->columns+image->columns % 2);
1162         image->storage_class=DirectClass;
1163         for (y=(ssize_t) image->rows-1; y >= 0; y--)
1164         {
1165           p=pixels+(image->rows-y-1)*bytes_per_line;
1166           q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);
1167           if (q == (Quantum *) NULL)
1168             break;
1169           for (x=0; x < (ssize_t) image->columns; x++)
1170           {
1171             pixel=(size_t) (*p++);
1172             pixel|=(*p++) << 8;
1173             red=((pixel & bmp_info.red_mask) << shift.red) >> 16;
1174             if (quantum_bits.red == 5)
1175               red|=((red & 0xe000) >> 5);
1176             if (quantum_bits.red <= 8)
1177               red|=((red & 0xff00) >> 8);
1178             green=((pixel & bmp_info.green_mask) << shift.green) >> 16;
1179             if (quantum_bits.green == 5)
1180               green|=((green & 0xe000) >> 5);
1181             if (quantum_bits.green == 6)
1182               green|=((green & 0xc000) >> 6);
1183             if (quantum_bits.green <= 8)
1184               green|=((green & 0xff00) >> 8);
1185             blue=((pixel & bmp_info.blue_mask) << shift.blue) >> 16;
1186             if (quantum_bits.blue == 5)
1187               blue|=((blue & 0xe000) >> 5);
1188             if (quantum_bits.blue <= 8)
1189               blue|=((blue & 0xff00) >> 8);
1190             alpha=((pixel & bmp_info.alpha_mask) << shift.alpha) >> 16;
1191             if (quantum_bits.alpha <= 8)
1192               alpha|=((alpha & 0xff00) >> 8);
1193             SetPixelRed(image,ScaleShortToQuantum((unsigned short) red),q);
1194             SetPixelGreen(image,ScaleShortToQuantum((unsigned short) green),q);
1195             SetPixelBlue(image,ScaleShortToQuantum((unsigned short) blue),q);
1196             SetPixelAlpha(image,OpaqueAlpha,q);
1197             if (image->alpha_trait == BlendPixelTrait)
1198               SetPixelAlpha(image,ScaleShortToQuantum((unsigned short) alpha),q);
1199             q+=GetPixelChannels(image);
1200           }
1201           if (SyncAuthenticPixels(image,exception) == MagickFalse)
1202             break;
1203           offset=(MagickOffsetType) (image->rows-y-1);
1204           if (image->previous == (Image *) NULL)
1205             {
1206               status=SetImageProgress(image,LoadImageTag,(MagickOffsetType)
1207                 (image->rows-y),image->rows);
1208               if (status == MagickFalse)
1209                 break;
1210             }
1211         }
1212         break;
1213       }
1214       case 24:
1215       {
1216         /*
1217           Convert DirectColor scanline.
1218         */
1219         bytes_per_line=4*((image->columns*24+31)/32);
1220         for (y=(ssize_t) image->rows-1; y >= 0; y--)
1221         {
1222           p=pixels+(image->rows-y-1)*bytes_per_line;
1223           q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);
1224           if (q == (Quantum *) NULL)
1225             break;
1226           for (x=0; x < (ssize_t) image->columns; x++)
1227           {
1228             SetPixelBlue(image,ScaleCharToQuantum(*p++),q);
1229             SetPixelGreen(image,ScaleCharToQuantum(*p++),q);
1230             SetPixelRed(image,ScaleCharToQuantum(*p++),q);
1231             SetPixelAlpha(image,OpaqueAlpha,q);
1232             q+=GetPixelChannels(image);
1233           }
1234           if (SyncAuthenticPixels(image,exception) == MagickFalse)
1235             break;
1236           offset=(MagickOffsetType) (image->rows-y-1);
1237           if (image->previous == (Image *) NULL)
1238             {
1239               status=SetImageProgress(image,LoadImageTag,(MagickOffsetType)
1240                 (image->rows-y),image->rows);
1241               if (status == MagickFalse)
1242                 break;
1243             }
1244         }
1245         break;
1246       }
1247       case 32:
1248       {
1249         /*
1250           Convert bitfield encoded DirectColor scanline.
1251         */
1252         if ((bmp_info.compression != BI_RGB) &&
1253             (bmp_info.compression != BI_BITFIELDS))
1254           {
1255             pixel_info=RelinquishVirtualMemory(pixel_info);
1256             ThrowReaderException(CorruptImageError,
1257               "UnrecognizedImageCompression");
1258           }
1259         bytes_per_line=4*(image->columns);
1260         for (y=(ssize_t) image->rows-1; y >= 0; y--)
1261         {
1262           size_t
1263             alpha,
1264             pixel;
1265
1266           p=pixels+(image->rows-y-1)*bytes_per_line;
1267           q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);
1268           if (q == (Quantum *) NULL)
1269             break;
1270           for (x=0; x < (ssize_t) image->columns; x++)
1271           {
1272             pixel=(size_t) (*p++);
1273             pixel|=((size_t) *p++ << 8);
1274             pixel|=((size_t) *p++ << 16);
1275             pixel|=((size_t) *p++ << 24);
1276             red=((pixel & bmp_info.red_mask) << shift.red) >> 16;
1277             if (quantum_bits.red == 8)
1278               red|=(red >> 8);
1279             green=((pixel & bmp_info.green_mask) << shift.green) >> 16;
1280             if (quantum_bits.green == 8)
1281               green|=(green >> 8);
1282             blue=((pixel & bmp_info.blue_mask) << shift.blue) >> 16;
1283             if (quantum_bits.blue == 8)
1284               blue|=(blue >> 8);
1285             alpha=((pixel & bmp_info.alpha_mask) << shift.alpha) >> 16;
1286             if (quantum_bits.alpha == 8)
1287               alpha|=(alpha >> 8);
1288             SetPixelRed(image,ScaleShortToQuantum((unsigned short) red),q);
1289             SetPixelGreen(image,ScaleShortToQuantum((unsigned short) green),q);
1290             SetPixelBlue(image,ScaleShortToQuantum((unsigned short) blue),q);
1291             SetPixelOpacity(image,OpaqueAlpha,q);
1292             if (image->alpha_trait == BlendPixelTrait)
1293               SetPixelAlpha(image,ScaleShortToQuantum((unsigned short) alpha),q);
1294             q+=GetPixelChannels(image);
1295           }
1296           if (SyncAuthenticPixels(image,exception) == MagickFalse)
1297             break;
1298           offset=(MagickOffsetType) (image->rows-y-1);
1299           if (image->previous == (Image *) NULL)
1300             {
1301               status=SetImageProgress(image,LoadImageTag,(MagickOffsetType)
1302                 (image->rows-y),image->rows);
1303               if (status == MagickFalse)
1304                 break;
1305             }
1306         }
1307         break;
1308       }
1309       default:
1310       {
1311         pixel_info=RelinquishVirtualMemory(pixel_info);
1312         ThrowReaderException(CorruptImageError,"ImproperImageHeader");
1313       }
1314     }
1315     pixel_info=RelinquishVirtualMemory(pixel_info);
1316     if (EOFBlob(image) != MagickFalse)
1317       {
1318         ThrowFileException(exception,CorruptImageError,"UnexpectedEndOfFile",
1319           image->filename);
1320         break;
1321       }
1322     if (bmp_info.height < 0)
1323       {
1324         Image
1325           *flipped_image;
1326
1327         /*
1328           Correct image orientation.
1329         */
1330         flipped_image=FlipImage(image,exception);
1331         if (flipped_image != (Image *) NULL)
1332           {
1333             DuplicateBlob(flipped_image,image);
1334             image=DestroyImage(image);
1335             image=flipped_image;
1336           }
1337       }
1338     /*
1339       Proceed to next image.
1340     */
1341     if (image_info->number_scenes != 0)
1342       if (image->scene >= (image_info->scene+image_info->number_scenes-1))
1343         break;
1344     *magick='\0';
1345     if (bmp_info.ba_offset != 0)
1346       {
1347         offset=SeekBlob(image,(MagickOffsetType) bmp_info.ba_offset,SEEK_SET);
1348         if (offset < 0)
1349           ThrowReaderException(CorruptImageError,"ImproperImageHeader");
1350       }
1351     count=ReadBlob(image,2,magick);
1352     if ((count == 2) && (IsBMP(magick,2) != MagickFalse))
1353       {
1354         /*
1355           Acquire next image structure.
1356         */
1357         AcquireNextImage(image_info,image,exception);
1358         if (GetNextImageInList(image) == (Image *) NULL)
1359           {
1360             image=DestroyImageList(image);
1361             return((Image *) NULL);
1362           }
1363         image=SyncNextImageInList(image);
1364         status=SetImageProgress(image,LoadImagesTag,TellBlob(image),
1365           GetBlobSize(image));
1366         if (status == MagickFalse)
1367           break;
1368       }
1369   } while (IsBMP(magick,2) != MagickFalse);
1370   (void) CloseBlob(image);
1371   return(GetFirstImageInList(image));
1372 }
1373 \f
1374 /*
1375 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1376 %                                                                             %
1377 %                                                                             %
1378 %                                                                             %
1379 %   R e g i s t e r B M P I m a g e                                           %
1380 %                                                                             %
1381 %                                                                             %
1382 %                                                                             %
1383 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1384 %
1385 %  RegisterBMPImage() adds attributes for the BMP image format to
1386 %  the list of supported formats.  The attributes include the image format
1387 %  tag, a method to read and/or write the format, whether the format
1388 %  supports the saving of more than one frame to the same file or blob,
1389 %  whether the format supports native in-memory I/O, and a brief
1390 %  description of the format.
1391 %
1392 %  The format of the RegisterBMPImage method is:
1393 %
1394 %      size_t RegisterBMPImage(void)
1395 %
1396 */
1397 ModuleExport size_t RegisterBMPImage(void)
1398 {
1399   MagickInfo
1400     *entry;
1401
1402   entry=SetMagickInfo("BMP");
1403   entry->decoder=(DecodeImageHandler *) ReadBMPImage;
1404   entry->encoder=(EncodeImageHandler *) WriteBMPImage;
1405   entry->magick=(IsImageFormatHandler *) IsBMP;
1406   entry->description=ConstantString("Microsoft Windows bitmap image");
1407   entry->module=ConstantString("BMP");
1408   entry->adjoin=MagickFalse;
1409   entry->seekable_stream=MagickTrue;
1410   (void) RegisterMagickInfo(entry);
1411   entry=SetMagickInfo("BMP2");
1412   entry->encoder=(EncodeImageHandler *) WriteBMPImage;
1413   entry->magick=(IsImageFormatHandler *) IsBMP;
1414   entry->description=ConstantString("Microsoft Windows bitmap image (V2)");
1415   entry->module=ConstantString("BMP");
1416   entry->adjoin=MagickFalse;
1417   entry->seekable_stream=MagickTrue;
1418   (void) RegisterMagickInfo(entry);
1419   entry=SetMagickInfo("BMP3");
1420   entry->encoder=(EncodeImageHandler *) WriteBMPImage;
1421   entry->magick=(IsImageFormatHandler *) IsBMP;
1422   entry->description=ConstantString("Microsoft Windows bitmap image (V3)");
1423   entry->module=ConstantString("BMP");
1424   entry->adjoin=MagickFalse;
1425   entry->seekable_stream=MagickTrue;
1426   (void) RegisterMagickInfo(entry);
1427   return(MagickImageCoderSignature);
1428 }
1429 \f
1430 /*
1431 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1432 %                                                                             %
1433 %                                                                             %
1434 %                                                                             %
1435 %   U n r e g i s t e r B M P I m a g e                                       %
1436 %                                                                             %
1437 %                                                                             %
1438 %                                                                             %
1439 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1440 %
1441 %  UnregisterBMPImage() removes format registrations made by the
1442 %  BMP module from the list of supported formats.
1443 %
1444 %  The format of the UnregisterBMPImage method is:
1445 %
1446 %      UnregisterBMPImage(void)
1447 %
1448 */
1449 ModuleExport void UnregisterBMPImage(void)
1450 {
1451   (void) UnregisterMagickInfo("BMP");
1452   (void) UnregisterMagickInfo("BMP2");
1453   (void) UnregisterMagickInfo("BMP3");
1454 }
1455 \f
1456 /*
1457 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1458 %                                                                             %
1459 %                                                                             %
1460 %                                                                             %
1461 %   W r i t e B M P I m a g e                                                 %
1462 %                                                                             %
1463 %                                                                             %
1464 %                                                                             %
1465 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1466 %
1467 %  WriteBMPImage() writes an image in Microsoft Windows bitmap encoded
1468 %  image format, version 3 for Windows or (if the image has a matte channel)
1469 %  version 4.
1470 %
1471 %  The format of the WriteBMPImage method is:
1472 %
1473 %      MagickBooleanType WriteBMPImage(const ImageInfo *image_info,
1474 %        Image *image,ExceptionInfo *exception)
1475 %
1476 %  A description of each parameter follows.
1477 %
1478 %    o image_info: the image info.
1479 %
1480 %    o image:  The image.
1481 %
1482 %    o exception: return any errors or warnings in this structure.
1483 %
1484 */
1485 static MagickBooleanType WriteBMPImage(const ImageInfo *image_info,Image *image,
1486   ExceptionInfo *exception)
1487 {
1488   BMPInfo
1489     bmp_info;
1490   const char
1491     *value;
1492
1493
1494   const StringInfo
1495     *profile;
1496
1497   MagickBooleanType
1498     have_color_info,
1499     status;
1500
1501   MagickOffsetType
1502     scene;
1503
1504   MemoryInfo
1505     *pixel_info;
1506
1507   register const Quantum
1508     *p;
1509
1510   register ssize_t
1511     i,
1512     x;
1513
1514   register unsigned char
1515     *q;
1516
1517   size_t
1518     bytes_per_line,
1519     type;
1520
1521   ssize_t
1522     y;
1523
1524   unsigned char
1525     *bmp_data,
1526     *pixels;
1527
1528   /*
1529     Open output image file.
1530   */
1531   assert(image_info != (const ImageInfo *) NULL);
1532   assert(image_info->signature == MagickSignature);
1533   assert(image != (Image *) NULL);
1534   assert(image->signature == MagickSignature);
1535   if (image->debug != MagickFalse)
1536     (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
1537   assert(exception != (ExceptionInfo *) NULL);
1538   assert(exception->signature == MagickSignature);
1539   status=OpenBlob(image_info,image,WriteBinaryBlobMode,exception);
1540   if (status == MagickFalse)
1541     return(status);
1542   type=4;
1543   if (LocaleCompare(image_info->magick,"BMP2") == 0)
1544     type=2;
1545   else
1546     if (LocaleCompare(image_info->magick,"BMP3") == 0)
1547       type=3;
1548
1549   value=GetImageOption(image_info,"bmp:format");
1550
1551   if (value != (char *) NULL)
1552     {
1553       (void) LogMagickEvent(CoderEvent,GetMagickModule(),
1554           "  Format=%s",value);
1555
1556       if (LocaleCompare(value,"bmp2") == 0)
1557         type=2;
1558       if (LocaleCompare(value,"bmp3") == 0)
1559         type=3;
1560       if (LocaleCompare(value,"bmp4") == 0)
1561         type=4;
1562     }
1563
1564   scene=0;
1565   do
1566   {
1567     /*
1568       Initialize BMP raster file header.
1569     */
1570     (void) TransformImageColorspace(image,sRGBColorspace,exception);
1571     (void) ResetMagickMemory(&bmp_info,0,sizeof(bmp_info));
1572     bmp_info.file_size=14+12;
1573     if (type > 2)
1574       bmp_info.file_size+=28;
1575     bmp_info.offset_bits=bmp_info.file_size;
1576     bmp_info.compression=BI_RGB;
1577     if ((image->storage_class == PseudoClass) && (image->colors > 256))
1578       (void) SetImageStorageClass(image,DirectClass,exception);
1579     if (image->storage_class != DirectClass)
1580       {
1581         /*
1582           Colormapped BMP raster.
1583         */
1584         bmp_info.bits_per_pixel=8;
1585         if (image->colors <= 2)
1586           bmp_info.bits_per_pixel=1;
1587         else
1588           if (image->colors <= 16)
1589             bmp_info.bits_per_pixel=4;
1590           else
1591             if (image->colors <= 256)
1592               bmp_info.bits_per_pixel=8;
1593         if (image_info->compression == RLECompression)
1594           bmp_info.bits_per_pixel=8;
1595         bmp_info.number_colors=1U << bmp_info.bits_per_pixel;
1596         if (image->alpha_trait == BlendPixelTrait)
1597           (void) SetImageStorageClass(image,DirectClass,exception);
1598         else
1599           if ((size_t) bmp_info.number_colors < image->colors)
1600             (void) SetImageStorageClass(image,DirectClass,exception);
1601           else
1602             {
1603               bmp_info.file_size+=3*(1UL << bmp_info.bits_per_pixel);
1604               bmp_info.offset_bits+=3*(1UL << bmp_info.bits_per_pixel);
1605               if (type > 2)
1606                 {
1607                   bmp_info.file_size+=(1UL << bmp_info.bits_per_pixel);
1608                   bmp_info.offset_bits+=(1UL << bmp_info.bits_per_pixel);
1609                 }
1610             }
1611       }
1612     if (image->storage_class == DirectClass)
1613       {
1614         /*
1615           Full color BMP raster.
1616         */
1617         bmp_info.number_colors=0;
1618         bmp_info.bits_per_pixel=(unsigned short)
1619           ((type > 3) && (image->alpha_trait == BlendPixelTrait) ? 32 : 24);
1620         bmp_info.compression=(unsigned int) ((type > 3) &&
1621           (image->alpha_trait == BlendPixelTrait) ?  BI_BITFIELDS : BI_RGB);
1622       }
1623     bytes_per_line=4*((image->columns*bmp_info.bits_per_pixel+31)/32);
1624     bmp_info.ba_offset=0;
1625     profile=GetImageProfile(image,"icc");
1626     have_color_info=(image->rendering_intent != UndefinedIntent) ||
1627       (profile != (StringInfo *) NULL) || (image->gamma != 0.0) ?  MagickTrue :
1628       MagickFalse;
1629     if (type == 2)
1630       bmp_info.size=12;
1631     else
1632       if ((type == 3) || ((image->alpha_trait != BlendPixelTrait) &&
1633           (have_color_info == MagickFalse)))
1634         {
1635           type=3;
1636           bmp_info.size=40;
1637         }
1638       else
1639         {
1640           int
1641             extra_size;
1642
1643           bmp_info.size=108;
1644           extra_size=68;
1645           if ((image->rendering_intent != UndefinedIntent) ||
1646               (profile != (StringInfo *) NULL))
1647             {
1648               bmp_info.size=124;
1649               extra_size+=16;
1650             }
1651           bmp_info.file_size+=extra_size;
1652           bmp_info.offset_bits+=extra_size;
1653         }
1654     bmp_info.width=(ssize_t) image->columns;
1655     bmp_info.height=(ssize_t) image->rows;
1656     bmp_info.planes=1;
1657     bmp_info.image_size=(unsigned int) (bytes_per_line*image->rows);
1658     bmp_info.file_size+=bmp_info.image_size;
1659     bmp_info.x_pixels=75*39;
1660     bmp_info.y_pixels=75*39;
1661     switch (image->units)
1662     {
1663       case UndefinedResolution:
1664       case PixelsPerInchResolution:
1665       {
1666         bmp_info.x_pixels=(unsigned int) (100.0*image->resolution.x/2.54);
1667         bmp_info.y_pixels=(unsigned int) (100.0*image->resolution.y/2.54);
1668         break;
1669       }
1670       case PixelsPerCentimeterResolution:
1671       {
1672         bmp_info.x_pixels=(unsigned int) (100.0*image->resolution.x);
1673         bmp_info.y_pixels=(unsigned int) (100.0*image->resolution.y);
1674         break;
1675       }
1676     }
1677     bmp_info.colors_important=bmp_info.number_colors;
1678     /*
1679       Convert MIFF to BMP raster pixels.
1680     */
1681     pixel_info=AcquireVirtualMemory((size_t) bmp_info.image_size,
1682       sizeof(*pixels));
1683     if (pixel_info == (MemoryInfo *) NULL)
1684       ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed");
1685     pixels=(unsigned char *) GetVirtualMemoryBlob(pixel_info);
1686     (void) ResetMagickMemory(pixels,0,(size_t) bmp_info.image_size);
1687     switch (bmp_info.bits_per_pixel)
1688     {
1689       case 1:
1690       {
1691         size_t
1692           bit,
1693           byte;
1694
1695         /*
1696           Convert PseudoClass image to a BMP monochrome image.
1697         */
1698         for (y=0; y < (ssize_t) image->rows; y++)
1699         {
1700           ssize_t
1701             offset;
1702
1703           p=GetVirtualPixels(image,0,y,image->columns,1,exception);
1704           if (p == (const Quantum *) NULL)
1705             break;
1706           q=pixels+(image->rows-y-1)*bytes_per_line;
1707           bit=0;
1708           byte=0;
1709           for (x=0; x < (ssize_t) image->columns; x++)
1710           {
1711             byte<<=1;
1712             byte|=GetPixelIndex(image,p) != 0 ? 0x01 : 0x00;
1713             bit++;
1714             if (bit == 8)
1715               {
1716                 *q++=(unsigned char) byte;
1717                 bit=0;
1718                 byte=0;
1719               }
1720              p+=GetPixelChannels(image);
1721            }
1722            if (bit != 0)
1723              {
1724                *q++=(unsigned char) (byte << (8-bit));
1725                x++;
1726              }
1727           offset=(ssize_t) (image->columns+7)/8;
1728           for (x=offset; x < (ssize_t) bytes_per_line; x++)
1729             *q++=0x00;
1730           if (image->previous == (Image *) NULL)
1731             {
1732               status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y,
1733                 image->rows);
1734               if (status == MagickFalse)
1735                 break;
1736             }
1737         }
1738         break;
1739       }
1740       case 4:
1741       {
1742         size_t
1743           byte,
1744           nibble;
1745
1746         ssize_t
1747           offset;
1748
1749         /*
1750           Convert PseudoClass image to a BMP monochrome image.
1751         */
1752         for (y=0; y < (ssize_t) image->rows; y++)
1753         {
1754           p=GetVirtualPixels(image,0,y,image->columns,1,exception);
1755           if (p == (const Quantum *) NULL)
1756             break;
1757           q=pixels+(image->rows-y-1)*bytes_per_line;
1758           nibble=0;
1759           byte=0;
1760           for (x=0; x < (ssize_t) image->columns; x++)
1761           {
1762             byte<<=4;
1763             byte|=((size_t) GetPixelIndex(image,p) & 0x0f);
1764             nibble++;
1765             if (nibble == 2)
1766               {
1767                 *q++=(unsigned char) byte;
1768                 nibble=0;
1769                 byte=0;
1770               }
1771             p+=GetPixelChannels(image);
1772           }
1773           if (nibble != 0)
1774             {
1775               *q++=(unsigned char) (byte << 4);
1776               x++;
1777             }
1778           offset=(ssize_t) (image->columns+1)/2;
1779           for (x=offset; x < (ssize_t) bytes_per_line; x++)
1780             *q++=0x00;
1781           if (image->previous == (Image *) NULL)
1782             {
1783               status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y,
1784                 image->rows);
1785               if (status == MagickFalse)
1786                 break;
1787             }
1788         }
1789         break;
1790       }
1791       case 8:
1792       {
1793         /*
1794           Convert PseudoClass packet to BMP pixel.
1795         */
1796         for (y=0; y < (ssize_t) image->rows; y++)
1797         {
1798           p=GetVirtualPixels(image,0,y,image->columns,1,exception);
1799           if (p == (const Quantum *) NULL)
1800             break;
1801           q=pixels+(image->rows-y-1)*bytes_per_line;
1802           for (x=0; x < (ssize_t) image->columns; x++)
1803           {
1804             *q++=(unsigned char) GetPixelIndex(image,p);
1805             p+=GetPixelChannels(image);
1806           }
1807           for ( ; x < (ssize_t) bytes_per_line; x++)
1808             *q++=0x00;
1809           if (image->previous == (Image *) NULL)
1810             {
1811               status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y,
1812                 image->rows);
1813               if (status == MagickFalse)
1814                 break;
1815             }
1816         }
1817         break;
1818       }
1819       case 24:
1820       {
1821         /*
1822           Convert DirectClass packet to BMP BGR888.
1823         */
1824         for (y=0; y < (ssize_t) image->rows; y++)
1825         {
1826           p=GetVirtualPixels(image,0,y,image->columns,1,exception);
1827           if (p == (const Quantum *) NULL)
1828             break;
1829           q=pixels+(image->rows-y-1)*bytes_per_line;
1830           for (x=0; x < (ssize_t) image->columns; x++)
1831           {
1832             *q++=ScaleQuantumToChar(GetPixelBlue(image,p));
1833             *q++=ScaleQuantumToChar(GetPixelGreen(image,p));
1834             *q++=ScaleQuantumToChar(GetPixelRed(image,p));
1835             p+=GetPixelChannels(image);
1836           }
1837           for (x=3L*(ssize_t) image->columns; x < (ssize_t) bytes_per_line; x++)
1838             *q++=0x00;
1839           if (image->previous == (Image *) NULL)
1840             {
1841               status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y,
1842                 image->rows);
1843               if (status == MagickFalse)
1844                 break;
1845             }
1846         }
1847         break;
1848       }
1849       case 32:
1850       {
1851         /*
1852           Convert DirectClass packet to ARGB8888 pixel.
1853         */
1854         for (y=0; y < (ssize_t) image->rows; y++)
1855         {
1856           p=GetVirtualPixels(image,0,y,image->columns,1,exception);
1857           if (p == (const Quantum *) NULL)
1858             break;
1859           q=pixels+(image->rows-y-1)*bytes_per_line;
1860           for (x=0; x < (ssize_t) image->columns; x++)
1861           {
1862             *q++=ScaleQuantumToChar(GetPixelBlue(image,p));
1863             *q++=ScaleQuantumToChar(GetPixelGreen(image,p));
1864             *q++=ScaleQuantumToChar(GetPixelRed(image,p));
1865             *q++=ScaleQuantumToChar(GetPixelAlpha(image,p));
1866             p+=GetPixelChannels(image);
1867           }
1868           if (image->previous == (Image *) NULL)
1869             {
1870               status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y,
1871                 image->rows);
1872               if (status == MagickFalse)
1873                 break;
1874             }
1875         }
1876         break;
1877       }
1878     }
1879     if ((type > 2) && (bmp_info.bits_per_pixel == 8))
1880       if (image_info->compression != NoCompression)
1881         {
1882           MemoryInfo
1883             *rle_info;
1884
1885           /*
1886             Convert run-length encoded raster pixels.
1887           */
1888           rle_info=AcquireVirtualMemory((size_t) (2*(bytes_per_line+2)+2),
1889             (image->rows+2)*sizeof(*pixels));
1890           if (rle_info == (MemoryInfo *) NULL)
1891             {
1892               pixel_info=RelinquishVirtualMemory(pixel_info);
1893               ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed");
1894             }
1895           bmp_data=(unsigned char *) GetVirtualMemoryBlob(rle_info);
1896           bmp_info.file_size-=bmp_info.image_size;
1897           bmp_info.image_size=(unsigned int) EncodeImage(image,bytes_per_line,
1898             pixels,bmp_data);
1899           bmp_info.file_size+=bmp_info.image_size;
1900           pixel_info=RelinquishVirtualMemory(pixel_info);
1901           pixel_info=rle_info;
1902           pixels=bmp_data;
1903           bmp_info.compression=BI_RLE8;
1904         }
1905     /*
1906       Write BMP for Windows, all versions, 14-byte header.
1907     */
1908     if (image->debug != MagickFalse)
1909       {
1910         (void) LogMagickEvent(CoderEvent,GetMagickModule(),
1911           "   Writing BMP version %.20g datastream",(double) type);
1912         if (image->storage_class == DirectClass)
1913           (void) LogMagickEvent(CoderEvent,GetMagickModule(),
1914             "   Storage class=DirectClass");
1915         else
1916           (void) LogMagickEvent(CoderEvent,GetMagickModule(),
1917             "   Storage class=PseudoClass");
1918         (void) LogMagickEvent(CoderEvent,GetMagickModule(),
1919           "   Image depth=%.20g",(double) image->depth);
1920         if (image->alpha_trait == BlendPixelTrait)
1921           (void) LogMagickEvent(CoderEvent,GetMagickModule(),
1922             "   Matte=True");
1923         else
1924           (void) LogMagickEvent(CoderEvent,GetMagickModule(),
1925             "   Matte=MagickFalse");
1926         (void) LogMagickEvent(CoderEvent,GetMagickModule(),
1927           "   BMP bits_per_pixel=%.20g",(double) bmp_info.bits_per_pixel);
1928         switch ((int) bmp_info.compression)
1929         {
1930            case BI_RGB:
1931            {
1932              (void) LogMagickEvent(CoderEvent,GetMagickModule(),
1933                "   Compression=BI_RGB");
1934              break;
1935            }
1936            case BI_RLE8:
1937            {
1938              (void) LogMagickEvent(CoderEvent,GetMagickModule(),
1939                "   Compression=BI_RLE8");
1940              break;
1941            }
1942            case BI_BITFIELDS:
1943            {
1944              (void) LogMagickEvent(CoderEvent,GetMagickModule(),
1945                "   Compression=BI_BITFIELDS");
1946              break;
1947            }
1948            default:
1949            {
1950              (void) LogMagickEvent(CoderEvent,GetMagickModule(),
1951                "   Compression=UNKNOWN (%u)",bmp_info.compression);
1952              break;
1953            }
1954         }
1955         if (bmp_info.number_colors == 0)
1956           (void) LogMagickEvent(CoderEvent,GetMagickModule(),
1957             "   Number_colors=unspecified");
1958         else
1959           (void) LogMagickEvent(CoderEvent,GetMagickModule(),
1960             "   Number_colors=%u",bmp_info.number_colors);
1961       }
1962     (void) WriteBlob(image,2,(unsigned char *) "BM");
1963     (void) WriteBlobLSBLong(image,bmp_info.file_size);
1964     (void) WriteBlobLSBLong(image,bmp_info.ba_offset);  /* always 0 */
1965     (void) WriteBlobLSBLong(image,bmp_info.offset_bits);
1966     if (type == 2)
1967       {
1968         /*
1969           Write 12-byte version 2 bitmap header.
1970         */
1971         (void) WriteBlobLSBLong(image,bmp_info.size);
1972         (void) WriteBlobLSBShort(image,(unsigned short) bmp_info.width);
1973         (void) WriteBlobLSBShort(image,(unsigned short) bmp_info.height);
1974         (void) WriteBlobLSBShort(image,bmp_info.planes);
1975         (void) WriteBlobLSBShort(image,bmp_info.bits_per_pixel);
1976       }
1977     else
1978       {
1979         /*
1980           Write 40-byte version 3+ bitmap header.
1981         */
1982         (void) WriteBlobLSBLong(image,bmp_info.size);
1983         (void) WriteBlobLSBLong(image,(unsigned int) bmp_info.width);
1984         (void) WriteBlobLSBLong(image,(unsigned int) bmp_info.height);
1985         (void) WriteBlobLSBShort(image,bmp_info.planes);
1986         (void) WriteBlobLSBShort(image,bmp_info.bits_per_pixel);
1987         (void) WriteBlobLSBLong(image,bmp_info.compression);
1988         (void) WriteBlobLSBLong(image,bmp_info.image_size);
1989         (void) WriteBlobLSBLong(image,bmp_info.x_pixels);
1990         (void) WriteBlobLSBLong(image,bmp_info.y_pixels);
1991         (void) WriteBlobLSBLong(image,bmp_info.number_colors);
1992         (void) WriteBlobLSBLong(image,bmp_info.colors_important);
1993       }
1994     if ((type > 3) && ((image->alpha_trait == BlendPixelTrait) ||
1995         (have_color_info != MagickFalse)))
1996       {
1997         /*
1998           Write the rest of the 108-byte BMP Version 4 header.
1999         */
2000         (void) WriteBlobLSBLong(image,0x00ff0000U);  /* Red mask */
2001         (void) WriteBlobLSBLong(image,0x0000ff00U);  /* Green mask */
2002         (void) WriteBlobLSBLong(image,0x000000ffU);  /* Blue mask */
2003         (void) WriteBlobLSBLong(image,0xff000000U);  /* Alpha mask */
2004         (void) WriteBlobLSBLong(image,0x73524742U);  /* sRGB */
2005         (void) WriteBlobLSBLong(image,(unsigned int)
2006           (image->chromaticity.red_primary.x*0x40000000));
2007         (void) WriteBlobLSBLong(image,(unsigned int)
2008           (image->chromaticity.red_primary.y*0x40000000));
2009         (void) WriteBlobLSBLong(image,(unsigned int)
2010           ((1.000f-(image->chromaticity.red_primary.x+
2011           image->chromaticity.red_primary.y))*0x40000000));
2012         (void) WriteBlobLSBLong(image,(unsigned int)
2013           (image->chromaticity.green_primary.x*0x40000000));
2014         (void) WriteBlobLSBLong(image,(unsigned int)
2015           (image->chromaticity.green_primary.y*0x40000000));
2016         (void) WriteBlobLSBLong(image,(unsigned int)
2017           ((1.000f-(image->chromaticity.green_primary.x+
2018           image->chromaticity.green_primary.y))*0x40000000));
2019         (void) WriteBlobLSBLong(image,(unsigned int)
2020           (image->chromaticity.blue_primary.x*0x40000000));
2021         (void) WriteBlobLSBLong(image,(unsigned int)
2022           (image->chromaticity.blue_primary.y*0x40000000));
2023         (void) WriteBlobLSBLong(image,(unsigned int)
2024           ((1.000f-(image->chromaticity.blue_primary.x+
2025           image->chromaticity.blue_primary.y))*0x40000000));
2026         (void) WriteBlobLSBLong(image,(unsigned int)
2027           (bmp_info.gamma_scale.x*0x10000));
2028         (void) WriteBlobLSBLong(image,(unsigned int)
2029           (bmp_info.gamma_scale.y*0x10000));
2030         (void) WriteBlobLSBLong(image,(unsigned int)
2031           (bmp_info.gamma_scale.z*0x10000));
2032         if ((image->rendering_intent != UndefinedIntent) ||
2033             (profile != (StringInfo *) NULL))
2034           {
2035             ssize_t
2036               intent;
2037
2038             switch ((int) image->rendering_intent)
2039             {
2040               case SaturationIntent:
2041               {
2042                 intent=LCS_GM_BUSINESS;
2043                 break;
2044               }
2045               case RelativeIntent:
2046               {
2047                 intent=LCS_GM_GRAPHICS;
2048                 break;
2049               }
2050               case PerceptualIntent:
2051               {
2052                 intent=LCS_GM_IMAGES;
2053                 break;
2054               }
2055               case AbsoluteIntent:
2056               {
2057                 intent=LCS_GM_ABS_COLORIMETRIC;
2058                 break;
2059               }
2060               default:
2061               {
2062                 intent=0;
2063                 break;
2064               }
2065             }
2066             (void) WriteBlobLSBLong(image,(unsigned int) intent);
2067             (void) WriteBlobLSBLong(image,0x00);  /* dummy profile data */
2068             (void) WriteBlobLSBLong(image,0x00);  /* dummy profile length */
2069             (void) WriteBlobLSBLong(image,0x00);  /* reserved */
2070           }
2071       }
2072     if (image->storage_class == PseudoClass)
2073       {
2074         unsigned char
2075           *bmp_colormap;
2076
2077         /*
2078           Dump colormap to file.
2079         */
2080         if (image->debug != MagickFalse)
2081           (void) LogMagickEvent(CoderEvent,GetMagickModule(),
2082             "  Colormap: %.20g entries",(double) image->colors);
2083         bmp_colormap=(unsigned char *) AcquireQuantumMemory((size_t) (1UL <<
2084           bmp_info.bits_per_pixel),4*sizeof(*bmp_colormap));
2085         if (bmp_colormap == (unsigned char *) NULL)
2086           ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed");
2087         q=bmp_colormap;
2088         for (i=0; i < (ssize_t) MagickMin((ssize_t) image->colors,(ssize_t) bmp_info.number_colors); i++)
2089         {
2090           *q++=ScaleQuantumToChar(ClampToQuantum(image->colormap[i].blue));
2091           *q++=ScaleQuantumToChar(ClampToQuantum(image->colormap[i].green));
2092           *q++=ScaleQuantumToChar(ClampToQuantum(image->colormap[i].red));
2093           if (type > 2)
2094             *q++=(unsigned char) 0x0;
2095         }
2096         for ( ; i < (ssize_t) (1UL << bmp_info.bits_per_pixel); i++)
2097         {
2098           *q++=(unsigned char) 0x00;
2099           *q++=(unsigned char) 0x00;
2100           *q++=(unsigned char) 0x00;
2101           if (type > 2)
2102             *q++=(unsigned char) 0x00;
2103         }
2104         if (type <= 2)
2105           (void) WriteBlob(image,(size_t) (3*(1L << bmp_info.bits_per_pixel)),
2106             bmp_colormap);
2107         else
2108           (void) WriteBlob(image,(size_t) (4*(1L << bmp_info.bits_per_pixel)),
2109             bmp_colormap);
2110         bmp_colormap=(unsigned char *) RelinquishMagickMemory(bmp_colormap);
2111       }
2112     if (image->debug != MagickFalse)
2113       (void) LogMagickEvent(CoderEvent,GetMagickModule(),
2114         "  Pixels:  %u bytes",bmp_info.image_size);
2115     (void) WriteBlob(image,(size_t) bmp_info.image_size,pixels);
2116     pixel_info=RelinquishVirtualMemory(pixel_info);
2117     if (GetNextImageInList(image) == (Image *) NULL)
2118       break;
2119     image=SyncNextImageInList(image);
2120     status=SetImageProgress(image,SaveImagesTag,scene++,
2121       GetImageListLength(image));
2122     if (status == MagickFalse)
2123       break;
2124   } while (image_info->adjoin != MagickFalse);
2125   (void) CloseBlob(image);
2126   return(MagickTrue);
2127 }