]> granicus.if.org Git - imagemagick/blob - coders/bmp.c
Fixed bug with -strip (-define png:exclude-chunk)
[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-2014 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     opacity,
539     red;
540
541   ssize_t
542     count,
543     y;
544
545   unsigned char
546     magick[12],
547     *pixels;
548
549   /*
550     Open image file.
551   */
552   assert(image_info != (const ImageInfo *) NULL);
553   assert(image_info->signature == MagickSignature);
554   if (image_info->debug != MagickFalse)
555     (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",
556       image_info->filename);
557   assert(exception != (ExceptionInfo *) NULL);
558   assert(exception->signature == MagickSignature);
559   image=AcquireImage(image_info,exception);
560   status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception);
561   if (status == MagickFalse)
562     {
563       image=DestroyImageList(image);
564       return((Image *) NULL);
565     }
566   /*
567     Determine if this a BMP file.
568   */
569   (void) ResetMagickMemory(&bmp_info,0,sizeof(bmp_info));
570   bmp_info.ba_offset=0;
571   start_position=0;
572   count=ReadBlob(image,2,magick);
573   do
574   {
575     PixelInfo
576       quantum_bits;
577
578     PixelPacket
579       shift;
580
581     size_t
582       profile_data,
583       profile_size;
584
585     /*
586       Verify BMP identifier.
587     */
588     if (bmp_info.ba_offset == 0)
589       start_position=TellBlob(image)-2;
590     bmp_info.ba_offset=0;
591     while (LocaleNCompare((char *) magick,"BA",2) == 0)
592     {
593       bmp_info.file_size=ReadBlobLSBLong(image);
594       bmp_info.ba_offset=ReadBlobLSBLong(image);
595       bmp_info.offset_bits=ReadBlobLSBLong(image);
596       count=ReadBlob(image,2,magick);
597       if (count != 2)
598         break;
599     }
600     if (image->debug != MagickFalse)
601       (void) LogMagickEvent(CoderEvent,GetMagickModule(),"  Magick: %c%c",
602         magick[0],magick[1]);
603     if ((count == 0) || ((LocaleNCompare((char *) magick,"BM",2) != 0) &&
604         (LocaleNCompare((char *) magick,"CI",2) != 0)))
605       ThrowReaderException(CorruptImageError,"ImproperImageHeader");
606     bmp_info.file_size=ReadBlobLSBLong(image);
607     (void) ReadBlobLSBLong(image);
608     bmp_info.offset_bits=ReadBlobLSBLong(image);
609     bmp_info.size=ReadBlobLSBLong(image);
610     if (image->debug != MagickFalse)
611       (void) LogMagickEvent(CoderEvent,GetMagickModule(),"  BMP size: %u",
612         bmp_info.size);
613     if (bmp_info.size == 12)
614       {
615         /*
616           OS/2 BMP image file.
617         */
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
774         if (bmp_info.size > 108)
775           {
776             size_t
777               intent;
778
779             /*
780               Read BMP Version 5 color management information.
781             */
782             intent=ReadBlobLSBLong(image);
783             switch ((int) intent)
784             {
785               case LCS_GM_BUSINESS:
786               {
787                 image->rendering_intent=SaturationIntent;
788                 break;
789               }
790               case LCS_GM_GRAPHICS:
791               {
792                 image->rendering_intent=RelativeIntent;
793                 break;
794               }
795               case LCS_GM_IMAGES:
796               {
797                 image->rendering_intent=PerceptualIntent;
798                 break;
799               }
800               case LCS_GM_ABS_COLORIMETRIC:
801               {
802                 image->rendering_intent=AbsoluteIntent;
803                 break;
804               }
805             }
806             profile_data=ReadBlobLSBLong(image);
807             profile_size=ReadBlobLSBLong(image);
808             (void) profile_data;
809             (void) profile_size;
810             (void) ReadBlobLSBLong(image);  /* Reserved byte */
811           }
812       }
813     if ((MagickSizeType) bmp_info.file_size > GetBlobSize(image))
814       (void) ThrowMagickException(exception,GetMagickModule(),CorruptImageError,
815         "LengthAndFilesizeDoNotMatch","`%s'",image->filename);
816     else
817       if ((MagickSizeType) bmp_info.file_size < GetBlobSize(image))
818         (void) ThrowMagickException(exception,GetMagickModule(),
819           CorruptImageWarning,"LengthAndFilesizeDoNotMatch","`%s'",
820           image->filename);
821     if (bmp_info.width <= 0)
822       ThrowReaderException(CorruptImageError,"NegativeOrZeroImageSize");
823     if (bmp_info.height == 0)
824       ThrowReaderException(CorruptImageError,"NegativeOrZeroImageSize");
825     if (bmp_info.planes != 1)
826       ThrowReaderException(CorruptImageError,"StaticPlanesValueNotEqualToOne");
827     if ((bmp_info.bits_per_pixel != 1) && (bmp_info.bits_per_pixel != 4) &&
828         (bmp_info.bits_per_pixel != 8) && (bmp_info.bits_per_pixel != 16) &&
829         (bmp_info.bits_per_pixel != 24) && (bmp_info.bits_per_pixel != 32))
830       ThrowReaderException(CorruptImageError,"UnrecognizedBitsPerPixel");
831     if (bmp_info.bits_per_pixel < 16 &&
832         bmp_info.number_colors > (1U << bmp_info.bits_per_pixel))
833       {
834         ThrowReaderException(CorruptImageError,
835             "UnrecognizedNumberOfColors");
836       }
837     if ((bmp_info.compression == 1) && (bmp_info.bits_per_pixel != 8))
838       ThrowReaderException(CorruptImageError,"UnrecognizedBitsPerPixel");
839     if ((bmp_info.compression == 2) && (bmp_info.bits_per_pixel != 4))
840       ThrowReaderException(CorruptImageError,"UnrecognizedBitsPerPixel");
841     if ((bmp_info.compression == 3) && (bmp_info.bits_per_pixel < 16))
842       ThrowReaderException(CorruptImageError,"UnrecognizedBitsPerPixel");
843     switch (bmp_info.compression)
844     {
845       case BI_RGB:
846       case BI_RLE8:
847       case BI_RLE4:
848       case BI_BITFIELDS:
849         break;
850       case BI_JPEG:
851         ThrowReaderException(CoderError,"JPEGCompressNotSupported");
852       case BI_PNG:
853         ThrowReaderException(CoderError,"PNGCompressNotSupported");
854       default:
855         ThrowReaderException(CorruptImageError,"UnrecognizedImageCompression");
856     }
857     image->columns=(size_t) MagickAbsoluteValue(bmp_info.width);
858     image->rows=(size_t) MagickAbsoluteValue(bmp_info.height);
859     image->depth=bmp_info.bits_per_pixel <= 8 ? bmp_info.bits_per_pixel : 8;
860     image->alpha_trait=((bmp_info.alpha_mask != 0) &&
861       (bmp_info.compression == BI_BITFIELDS)) ||
862       (bmp_info.bits_per_pixel == 32) ? BlendPixelTrait : UndefinedPixelTrait;
863     if (bmp_info.bits_per_pixel < 16)
864       {
865         size_t
866           one;
867
868         image->storage_class=PseudoClass;
869         image->colors=bmp_info.number_colors;
870         one=1;
871         if (image->colors == 0)
872           image->colors=one << bmp_info.bits_per_pixel;
873       }
874     if (image->storage_class == PseudoClass)
875       {
876         unsigned char
877           *bmp_colormap;
878
879         size_t
880           packet_size;
881
882         /*
883           Read BMP raster colormap.
884         */
885         if (image->debug != MagickFalse)
886           (void) LogMagickEvent(CoderEvent,GetMagickModule(),
887             "  Reading colormap of %.20g colors",(double) image->colors);
888         if (AcquireImageColormap(image,image->colors,exception) == MagickFalse)
889           ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
890         bmp_colormap=(unsigned char *) AcquireQuantumMemory((size_t)
891           image->colors,4*sizeof(*bmp_colormap));
892         if (bmp_colormap == (unsigned char *) NULL)
893           ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
894         if ((bmp_info.size == 12) || (bmp_info.size == 64))
895           packet_size=3;
896         else
897           packet_size=4;
898         offset=SeekBlob(image,start_position+14+bmp_info.size,SEEK_SET);
899         if (offset < 0)
900           ThrowReaderException(CorruptImageError,"ImproperImageHeader");
901         count=ReadBlob(image,packet_size*image->colors,bmp_colormap);
902         if (count != (ssize_t) (packet_size*image->colors))
903           ThrowReaderException(CorruptImageError,"InsufficientImageDataInFile");
904         p=bmp_colormap;
905         for (i=0; i < (ssize_t) image->colors; i++)
906         {
907           image->colormap[i].blue=(MagickRealType) ScaleCharToQuantum(*p++);
908           image->colormap[i].green=(MagickRealType) ScaleCharToQuantum(*p++);
909           image->colormap[i].red=(MagickRealType) ScaleCharToQuantum(*p++);
910           if (packet_size == 4)
911             p++;
912         }
913         bmp_colormap=(unsigned char *) RelinquishMagickMemory(bmp_colormap);
914       }
915     image->resolution.x=(double) bmp_info.x_pixels/100.0;
916     image->resolution.y=(double) bmp_info.y_pixels/100.0;
917     image->units=PixelsPerCentimeterResolution;
918     if ((image_info->ping != MagickFalse) && (image_info->number_scenes != 0))
919       if (image->scene >= (image_info->scene+image_info->number_scenes-1))
920         break;
921     /*
922       Read image data.
923     */
924     offset=SeekBlob(image,start_position+bmp_info.offset_bits,SEEK_SET);
925     if (offset < 0)
926       ThrowReaderException(CorruptImageError,"ImproperImageHeader");
927     if (bmp_info.compression == BI_RLE4)
928       bmp_info.bits_per_pixel<<=1;
929     bytes_per_line=4*((image->columns*bmp_info.bits_per_pixel+31)/32);
930     length=(size_t) bytes_per_line*image->rows;
931     pixel_info=AcquireVirtualMemory((size_t) image->rows,
932       MagickMax(bytes_per_line,image->columns+256UL)*sizeof(*pixels));
933     if (pixel_info == (MemoryInfo *) NULL)
934       ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
935     pixels=(unsigned char *) GetVirtualMemoryBlob(pixel_info);
936     if ((bmp_info.compression == BI_RGB) ||
937         (bmp_info.compression == BI_BITFIELDS))
938       {
939         if (image->debug != MagickFalse)
940           (void) LogMagickEvent(CoderEvent,GetMagickModule(),
941             "  Reading pixels (%.20g bytes)",(double) length);
942         count=ReadBlob(image,length,pixels);
943         if (count != (ssize_t) length)
944           {
945             pixel_info=RelinquishVirtualMemory(pixel_info);
946             ThrowReaderException(CorruptImageError,
947               "InsufficientImageDataInFile");
948           }
949       }
950     else
951       {
952         /*
953           Convert run-length encoded raster pixels.
954         */
955         status=DecodeImage(image,bmp_info.compression,pixels);
956         if (status == MagickFalse)
957           {
958             pixel_info=RelinquishVirtualMemory(pixel_info);
959             ThrowReaderException(CorruptImageError,
960               "UnableToRunlengthDecodeImage");
961           }
962       }
963     /*
964       Convert BMP raster image to pixel packets.
965     */
966     if (bmp_info.compression == BI_RGB)
967       {
968         bmp_info.alpha_mask=image->alpha_trait == BlendPixelTrait ?
969           0xff000000U : 0U;
970         bmp_info.red_mask=0x00ff0000U;
971         bmp_info.green_mask=0x0000ff00U;
972         bmp_info.blue_mask=0x000000ffU;
973         if (bmp_info.bits_per_pixel == 16)
974           {
975             /*
976               RGB555.
977             */
978             bmp_info.red_mask=0x00007c00U;
979             bmp_info.green_mask=0x000003e0U;
980             bmp_info.blue_mask=0x0000001fU;
981           }
982       }
983     if ((bmp_info.bits_per_pixel == 16) || (bmp_info.bits_per_pixel == 32))
984       {
985         register size_t
986           sample;
987
988         /*
989           Get shift and quantum bits info from bitfield masks.
990         */
991         (void) ResetMagickMemory(&shift,0,sizeof(shift));
992         (void) ResetMagickMemory(&quantum_bits,0,sizeof(quantum_bits));
993         if (bmp_info.red_mask != 0)
994           while (((bmp_info.red_mask << shift.red) & 0x80000000UL) == 0)
995             shift.red++;
996         if (bmp_info.green_mask != 0)
997           while (((bmp_info.green_mask << shift.green) & 0x80000000UL) == 0)
998             shift.green++;
999         if (bmp_info.blue_mask != 0)
1000           while (((bmp_info.blue_mask << shift.blue) & 0x80000000UL) == 0)
1001             shift.blue++;
1002         if (bmp_info.alpha_mask != 0)
1003           while (((bmp_info.alpha_mask << shift.alpha) & 0x80000000UL) == 0)
1004             shift.alpha++;
1005         sample=shift.red;
1006         while (((bmp_info.red_mask << sample) & 0x80000000UL) != 0)
1007           sample++;
1008         quantum_bits.red=(MagickRealType) (sample-shift.red);
1009         sample=shift.green;
1010         while (((bmp_info.green_mask << sample) & 0x80000000UL) != 0)
1011           sample++;
1012         quantum_bits.green=(MagickRealType) (sample-shift.green);
1013         sample=shift.blue;
1014         while (((bmp_info.blue_mask << sample) & 0x80000000UL) != 0)
1015           sample++;
1016         quantum_bits.blue=(MagickRealType) (sample-shift.blue);
1017         sample=shift.alpha;
1018         while (((bmp_info.alpha_mask << sample) & 0x80000000UL) != 0)
1019           sample++;
1020         quantum_bits.alpha=(MagickRealType) (sample-shift.alpha);
1021       }
1022     switch (bmp_info.bits_per_pixel)
1023     {
1024       case 1:
1025       {
1026         /*
1027           Convert bitmap scanline.
1028         */
1029         for (y=(ssize_t) image->rows-1; y >= 0; y--)
1030         {
1031           p=pixels+(image->rows-y-1)*bytes_per_line;
1032           q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);
1033           if (q == (Quantum *) NULL)
1034             break;
1035           for (x=0; x < ((ssize_t) image->columns-7); x+=8)
1036           {
1037             for (bit=0; bit < 8; bit++)
1038             {
1039               index=(Quantum) (((*p) & (0x80 >> bit)) != 0 ? 0x01 : 0x00);
1040               SetPixelIndex(image,index,q);
1041               q+=GetPixelChannels(image);
1042             }
1043             p++;
1044           }
1045           if ((image->columns % 8) != 0)
1046             {
1047               for (bit=0; bit < (image->columns % 8); bit++)
1048               {
1049                 index=(Quantum) (((*p) & (0x80 >> bit)) != 0 ? 0x01 : 0x00);
1050                 SetPixelIndex(image,index,q);
1051                 q+=GetPixelChannels(image);
1052               }
1053               p++;
1054             }
1055           if (SyncAuthenticPixels(image,exception) == MagickFalse)
1056             break;
1057           if (image->previous == (Image *) NULL)
1058             {
1059               status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y,
1060                 image->rows);
1061               if (status == MagickFalse)
1062                 break;
1063             }
1064         }
1065         (void) SyncImage(image,exception);
1066         break;
1067       }
1068       case 4:
1069       {
1070         /*
1071           Convert PseudoColor scanline.
1072         */
1073         for (y=(ssize_t) image->rows-1; y >= 0; y--)
1074         {
1075           p=pixels+(image->rows-y-1)*bytes_per_line;
1076           q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);
1077           if (q == (Quantum *) NULL)
1078             break;
1079           for (x=0; x < ((ssize_t) image->columns-1); x+=2)
1080           {
1081             index=ConstrainColormapIndex(image,(*p >> 4) & 0x0f,exception);
1082             SetPixelIndex(image,index,q);
1083             q+=GetPixelChannels(image);
1084             index=ConstrainColormapIndex(image,*p & 0x0f,exception);
1085             SetPixelIndex(image,index,q);
1086             q+=GetPixelChannels(image);
1087             p++;
1088           }
1089           if ((image->columns % 2) != 0)
1090             {
1091               index=ConstrainColormapIndex(image,(*p >> 4) & 0xf,exception);
1092               SetPixelIndex(image,index,q);
1093               q+=GetPixelChannels(image);
1094               p++;
1095             }
1096           if (SyncAuthenticPixels(image,exception) == MagickFalse)
1097             break;
1098           if (image->previous == (Image *) NULL)
1099             {
1100               status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y,
1101                 image->rows);
1102               if (status == MagickFalse)
1103                 break;
1104             }
1105         }
1106         (void) SyncImage(image,exception);
1107         break;
1108       }
1109       case 8:
1110       {
1111         /*
1112           Convert PseudoColor scanline.
1113         */
1114         if ((bmp_info.compression == BI_RLE8) ||
1115             (bmp_info.compression == BI_RLE4))
1116           bytes_per_line=image->columns;
1117         for (y=(ssize_t) image->rows-1; y >= 0; y--)
1118         {
1119           p=pixels+(image->rows-y-1)*bytes_per_line;
1120           q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);
1121           if (q == (Quantum *) NULL)
1122             break;
1123           for (x=(ssize_t) image->columns; x != 0; --x)
1124           {
1125             index=ConstrainColormapIndex(image,*p++,exception);
1126             SetPixelIndex(image,index,q);
1127             q+=GetPixelChannels(image);
1128           }
1129           if (SyncAuthenticPixels(image,exception) == MagickFalse)
1130             break;
1131           offset=(MagickOffsetType) (image->rows-y-1);
1132           if (image->previous == (Image *) NULL)
1133             {
1134               status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y,
1135                 image->rows);
1136               if (status == MagickFalse)
1137                 break;
1138             }
1139         }
1140         (void) SyncImage(image,exception);
1141         break;
1142       }
1143       case 16:
1144       {
1145         size_t
1146           pixel;
1147
1148         /*
1149           Convert bitfield encoded 16-bit PseudoColor scanline.
1150         */
1151         if (bmp_info.compression != BI_RGB &&
1152             bmp_info.compression != BI_BITFIELDS)
1153           {
1154             pixel_info=RelinquishVirtualMemory(pixel_info);
1155             ThrowReaderException(CorruptImageError,
1156               "UnrecognizedImageCompression");
1157           }
1158         bytes_per_line=2*(image->columns+image->columns % 2);
1159         image->storage_class=DirectClass;
1160         for (y=(ssize_t) image->rows-1; y >= 0; y--)
1161         {
1162           p=pixels+(image->rows-y-1)*bytes_per_line;
1163           q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);
1164           if (q == (Quantum *) NULL)
1165             break;
1166           for (x=0; x < (ssize_t) image->columns; x++)
1167           {
1168             pixel=(size_t) (*p++);
1169             pixel|=(*p++) << 8;
1170             red=((pixel & bmp_info.red_mask) << shift.red) >> 16;
1171             if (quantum_bits.red == 5)
1172               red|=((red & 0xe000) >> 5);
1173             if (quantum_bits.red <= 8)
1174               red|=((red & 0xff00) >> 8);
1175             green=((pixel & bmp_info.green_mask) << shift.green) >> 16;
1176             if (quantum_bits.green == 5)
1177               green|=((green & 0xe000) >> 5);
1178             if (quantum_bits.green == 6)
1179               green|=((green & 0xc000) >> 6);
1180             if (quantum_bits.green <= 8)
1181               green|=((green & 0xff00) >> 8);
1182             blue=((pixel & bmp_info.blue_mask) << shift.blue) >> 16;
1183             if (quantum_bits.blue == 5)
1184               blue|=((blue & 0xe000) >> 5);
1185             if (quantum_bits.blue <= 8)
1186               blue|=((blue & 0xff00) >> 8);
1187             opacity=((pixel & bmp_info.alpha_mask) << shift.alpha) >> 16;
1188             if (quantum_bits.alpha <= 8)
1189               opacity|=((opacity & 0xff00) >> 8);
1190             SetPixelRed(image,ScaleShortToQuantum((unsigned short) red),q);
1191             SetPixelGreen(image,ScaleShortToQuantum((unsigned short) green),q);
1192             SetPixelBlue(image,ScaleShortToQuantum((unsigned short) blue),q);
1193             SetPixelAlpha(image,OpaqueAlpha,q);
1194             if (image->alpha_trait == BlendPixelTrait)
1195               SetPixelAlpha(image,ScaleShortToQuantum((unsigned short)
1196                 opacity),q);
1197             q+=GetPixelChannels(image);
1198           }
1199           if (SyncAuthenticPixels(image,exception) == MagickFalse)
1200             break;
1201           offset=(MagickOffsetType) (image->rows-y-1);
1202           if (image->previous == (Image *) NULL)
1203             {
1204               status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y,
1205                 image->rows);
1206               if (status == MagickFalse)
1207                 break;
1208             }
1209         }
1210         break;
1211       }
1212       case 24:
1213       {
1214         /*
1215           Convert DirectColor scanline.
1216         */
1217         bytes_per_line=4*((image->columns*24+31)/32);
1218         for (y=(ssize_t) image->rows-1; y >= 0; y--)
1219         {
1220           p=pixels+(image->rows-y-1)*bytes_per_line;
1221           q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);
1222           if (q == (Quantum *) NULL)
1223             break;
1224           for (x=0; x < (ssize_t) image->columns; x++)
1225           {
1226             SetPixelBlue(image,ScaleCharToQuantum(*p++),q);
1227             SetPixelGreen(image,ScaleCharToQuantum(*p++),q);
1228             SetPixelRed(image,ScaleCharToQuantum(*p++),q);
1229             SetPixelAlpha(image,OpaqueAlpha,q);
1230             q+=GetPixelChannels(image);
1231           }
1232           if (SyncAuthenticPixels(image,exception) == MagickFalse)
1233             break;
1234           offset=(MagickOffsetType) (image->rows-y-1);
1235           if (image->previous == (Image *) NULL)
1236             {
1237               status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y,
1238                 image->rows);
1239               if (status == MagickFalse)
1240                 break;
1241             }
1242         }
1243         break;
1244       }
1245       case 32:
1246       {
1247         /*
1248           Convert bitfield encoded DirectColor scanline.
1249         */
1250         if ((bmp_info.compression != BI_RGB) &&
1251             (bmp_info.compression != BI_BITFIELDS))
1252           {
1253             pixel_info=RelinquishVirtualMemory(pixel_info);
1254             ThrowReaderException(CorruptImageError,
1255               "UnrecognizedImageCompression");
1256           }
1257         bytes_per_line=4*(image->columns);
1258         for (y=(ssize_t) image->rows-1; y >= 0; y--)
1259         {
1260           size_t
1261             pixel;
1262
1263           p=pixels+(image->rows-y-1)*bytes_per_line;
1264           q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);
1265           if (q == (Quantum *) NULL)
1266             break;
1267           for (x=0; x < (ssize_t) image->columns; x++)
1268           {
1269             pixel=(size_t) (*p++);
1270             pixel|=(*p++ << 8);
1271             pixel|=(*p++ << 16);
1272             pixel|=(*p++ << 24);
1273             red=((pixel & bmp_info.red_mask) << shift.red) >> 16;
1274             if (quantum_bits.red == 8)
1275               red|=(red >> 8);
1276             green=((pixel & bmp_info.green_mask) << shift.green) >> 16;
1277             if (quantum_bits.green == 8)
1278               green|=(green >> 8);
1279             blue=((pixel & bmp_info.blue_mask) << shift.blue) >> 16;
1280             if (quantum_bits.blue == 8)
1281               blue|=(blue >> 8);
1282             opacity=((pixel & bmp_info.alpha_mask) << shift.alpha) >> 16;
1283             if (quantum_bits.alpha == 8)
1284               opacity|=(opacity >> 8);
1285             SetPixelRed(image,ScaleShortToQuantum((unsigned short) red),q);
1286             SetPixelGreen(image,ScaleShortToQuantum((unsigned short) green),q);
1287             SetPixelBlue(image,ScaleShortToQuantum((unsigned short) blue),q);
1288             SetPixelAlpha(image,OpaqueAlpha,q);
1289             if (image->alpha_trait == BlendPixelTrait)
1290               SetPixelAlpha(image,ScaleShortToQuantum((unsigned short)
1291                 opacity),q);
1292             q+=GetPixelChannels(image);
1293           }
1294           if (SyncAuthenticPixels(image,exception) == MagickFalse)
1295             break;
1296           offset=(MagickOffsetType) (image->rows-y-1);
1297           if (image->previous == (Image *) NULL)
1298             {
1299               status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y,
1300                 image->rows);
1301               if (status == MagickFalse)
1302                 break;
1303             }
1304         }
1305         break;
1306       }
1307       default:
1308       {
1309         pixel_info=RelinquishVirtualMemory(pixel_info);
1310         ThrowReaderException(CorruptImageError,"ImproperImageHeader");
1311       }
1312     }
1313     pixel_info=RelinquishVirtualMemory(pixel_info);
1314     if (EOFBlob(image) != MagickFalse)
1315       {
1316         ThrowFileException(exception,CorruptImageError,"UnexpectedEndOfFile",
1317           image->filename);
1318         break;
1319       }
1320     if (bmp_info.height < 0)
1321       {
1322         Image
1323           *flipped_image;
1324
1325         /*
1326           Correct image orientation.
1327         */
1328         flipped_image=FlipImage(image,exception);
1329         if (flipped_image != (Image *) NULL)
1330           {
1331             DuplicateBlob(flipped_image,image);
1332             image=DestroyImage(image);
1333             image=flipped_image;
1334           }
1335       }
1336     /*
1337       Proceed to next image.
1338     */
1339     if (image_info->number_scenes != 0)
1340       if (image->scene >= (image_info->scene+image_info->number_scenes-1))
1341         break;
1342     *magick='\0';
1343     if (bmp_info.ba_offset != 0)
1344       {
1345         offset=SeekBlob(image,(MagickOffsetType) bmp_info.ba_offset,SEEK_SET);
1346         if (offset < 0)
1347           ThrowReaderException(CorruptImageError,"ImproperImageHeader");
1348       }
1349     count=ReadBlob(image,2,magick);
1350     if ((count == 2) && (IsBMP(magick,2) != MagickFalse))
1351       {
1352         /*
1353           Acquire next image structure.
1354         */
1355         AcquireNextImage(image_info,image,exception);
1356         if (GetNextImageInList(image) == (Image *) NULL)
1357           {
1358             image=DestroyImageList(image);
1359             return((Image *) NULL);
1360           }
1361         image=SyncNextImageInList(image);
1362         status=SetImageProgress(image,LoadImagesTag,TellBlob(image),
1363           GetBlobSize(image));
1364         if (status == MagickFalse)
1365           break;
1366       }
1367   } while (IsBMP(magick,2) != MagickFalse);
1368   (void) CloseBlob(image);
1369   return(GetFirstImageInList(image));
1370 }
1371 \f
1372 /*
1373 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1374 %                                                                             %
1375 %                                                                             %
1376 %                                                                             %
1377 %   R e g i s t e r B M P I m a g e                                           %
1378 %                                                                             %
1379 %                                                                             %
1380 %                                                                             %
1381 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1382 %
1383 %  RegisterBMPImage() adds attributes for the BMP image format to
1384 %  the list of supported formats.  The attributes include the image format
1385 %  tag, a method to read and/or write the format, whether the format
1386 %  supports the saving of more than one frame to the same file or blob,
1387 %  whether the format supports native in-memory I/O, and a brief
1388 %  description of the format.
1389 %
1390 %  The format of the RegisterBMPImage method is:
1391 %
1392 %      size_t RegisterBMPImage(void)
1393 %
1394 */
1395 ModuleExport size_t RegisterBMPImage(void)
1396 {
1397   MagickInfo
1398     *entry;
1399
1400   entry=SetMagickInfo("BMP");
1401   entry->decoder=(DecodeImageHandler *) ReadBMPImage;
1402   entry->encoder=(EncodeImageHandler *) WriteBMPImage;
1403   entry->magick=(IsImageFormatHandler *) IsBMP;
1404   entry->description=ConstantString("Microsoft Windows bitmap image");
1405   entry->module=ConstantString("BMP");
1406   entry->adjoin=MagickFalse;
1407   entry->seekable_stream=MagickTrue;
1408   (void) RegisterMagickInfo(entry);
1409   entry=SetMagickInfo("BMP2");
1410   entry->encoder=(EncodeImageHandler *) WriteBMPImage;
1411   entry->magick=(IsImageFormatHandler *) IsBMP;
1412   entry->description=ConstantString("Microsoft Windows bitmap image (V2)");
1413   entry->module=ConstantString("BMP");
1414   entry->adjoin=MagickFalse;
1415   entry->seekable_stream=MagickTrue;
1416   (void) RegisterMagickInfo(entry);
1417   entry=SetMagickInfo("BMP3");
1418   entry->encoder=(EncodeImageHandler *) WriteBMPImage;
1419   entry->magick=(IsImageFormatHandler *) IsBMP;
1420   entry->description=ConstantString("Microsoft Windows bitmap image (V3)");
1421   entry->module=ConstantString("BMP");
1422   entry->adjoin=MagickFalse;
1423   entry->seekable_stream=MagickTrue;
1424   (void) RegisterMagickInfo(entry);
1425   return(MagickImageCoderSignature);
1426 }
1427 \f
1428 /*
1429 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1430 %                                                                             %
1431 %                                                                             %
1432 %                                                                             %
1433 %   U n r e g i s t e r B M P I m a g e                                       %
1434 %                                                                             %
1435 %                                                                             %
1436 %                                                                             %
1437 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1438 %
1439 %  UnregisterBMPImage() removes format registrations made by the
1440 %  BMP module from the list of supported formats.
1441 %
1442 %  The format of the UnregisterBMPImage method is:
1443 %
1444 %      UnregisterBMPImage(void)
1445 %
1446 */
1447 ModuleExport void UnregisterBMPImage(void)
1448 {
1449   (void) UnregisterMagickInfo("BMP");
1450   (void) UnregisterMagickInfo("BMP2");
1451   (void) UnregisterMagickInfo("BMP3");
1452 }
1453 \f
1454 /*
1455 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1456 %                                                                             %
1457 %                                                                             %
1458 %                                                                             %
1459 %   W r i t e B M P I m a g e                                                 %
1460 %                                                                             %
1461 %                                                                             %
1462 %                                                                             %
1463 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1464 %
1465 %  WriteBMPImage() writes an image in Microsoft Windows bitmap encoded
1466 %  image format, version 3 for Windows or (if the image has a matte channel)
1467 %  version 4.
1468 %
1469 %  The format of the WriteBMPImage method is:
1470 %
1471 %      MagickBooleanType WriteBMPImage(const ImageInfo *image_info,
1472 %        Image *image,ExceptionInfo *exception)
1473 %
1474 %  A description of each parameter follows.
1475 %
1476 %    o image_info: the image info.
1477 %
1478 %    o image:  The image.
1479 %
1480 %    o exception: return any errors or warnings in this structure.
1481 %
1482 */
1483 static MagickBooleanType WriteBMPImage(const ImageInfo *image_info,Image *image,
1484   ExceptionInfo *exception)
1485 {
1486   BMPInfo
1487     bmp_info;
1488   const char
1489     *value;
1490
1491
1492   const StringInfo
1493     *profile;
1494
1495   MagickBooleanType
1496     have_color_info,
1497     status;
1498
1499   MagickOffsetType
1500     scene;
1501
1502   MemoryInfo
1503     *pixel_info;
1504
1505   register const Quantum
1506     *p;
1507
1508   register ssize_t
1509     i,
1510     x;
1511
1512   register unsigned char
1513     *q;
1514
1515   size_t
1516     bytes_per_line,
1517     type;
1518
1519   ssize_t
1520     y;
1521
1522   unsigned char
1523     *bmp_data,
1524     *pixels;
1525
1526   /*
1527     Open output image file.
1528   */
1529   assert(image_info != (const ImageInfo *) NULL);
1530   assert(image_info->signature == MagickSignature);
1531   assert(image != (Image *) NULL);
1532   assert(image->signature == MagickSignature);
1533   if (image->debug != MagickFalse)
1534     (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
1535   assert(exception != (ExceptionInfo *) NULL);
1536   assert(exception->signature == MagickSignature);
1537   status=OpenBlob(image_info,image,WriteBinaryBlobMode,exception);
1538   if (status == MagickFalse)
1539     return(status);
1540   type=4;
1541   if (LocaleCompare(image_info->magick,"BMP2") == 0)
1542     type=2;
1543   else
1544     if (LocaleCompare(image_info->magick,"BMP3") == 0)
1545       type=3;
1546
1547   value=GetImageOption(image_info,"bmp:format");
1548
1549   if (value != (char *) NULL)
1550     {
1551       (void) LogMagickEvent(CoderEvent,GetMagickModule(),
1552           "  Format=%s",value);
1553
1554       if (LocaleCompare(value,"bmp2") == 0)
1555         type=2;
1556       if (LocaleCompare(value,"bmp3") == 0)
1557         type=3;
1558       if (LocaleCompare(value,"bmp4") == 0)
1559         type=4;
1560     }
1561
1562   scene=0;
1563   do
1564   {
1565     /*
1566       Initialize BMP raster file header.
1567     */
1568     (void) TransformImageColorspace(image,sRGBColorspace,exception);
1569     (void) ResetMagickMemory(&bmp_info,0,sizeof(bmp_info));
1570     bmp_info.file_size=14+12;
1571     if (type > 2)
1572       bmp_info.file_size+=28;
1573     bmp_info.offset_bits=bmp_info.file_size;
1574     bmp_info.compression=BI_RGB;
1575     if ((image->storage_class == PseudoClass) && (image->colors > 256))
1576       (void) SetImageStorageClass(image,DirectClass,exception);
1577     if (image->storage_class != DirectClass)
1578       {
1579         /*
1580           Colormapped BMP raster.
1581         */
1582         bmp_info.bits_per_pixel=8;
1583         if (image->colors <= 2)
1584           bmp_info.bits_per_pixel=1;
1585         else
1586           if (image->colors <= 16)
1587             bmp_info.bits_per_pixel=4;
1588           else
1589             if (image->colors <= 256)
1590               bmp_info.bits_per_pixel=8;
1591         if (image_info->compression == RLECompression)
1592           bmp_info.bits_per_pixel=8;
1593         bmp_info.number_colors=1U << bmp_info.bits_per_pixel;
1594         if (image->alpha_trait == BlendPixelTrait)
1595           (void) SetImageStorageClass(image,DirectClass,exception);
1596         else
1597           if ((size_t) bmp_info.number_colors < image->colors)
1598             (void) SetImageStorageClass(image,DirectClass,exception);
1599           else
1600             {
1601               bmp_info.file_size+=3*(1UL << bmp_info.bits_per_pixel);
1602               bmp_info.offset_bits+=3*(1UL << bmp_info.bits_per_pixel);
1603               if (type > 2)
1604                 {
1605                   bmp_info.file_size+=(1UL << bmp_info.bits_per_pixel);
1606                   bmp_info.offset_bits+=(1UL << bmp_info.bits_per_pixel);
1607                 }
1608             }
1609       }
1610     if (image->storage_class == DirectClass)
1611       {
1612         /*
1613           Full color BMP raster.
1614         */
1615         bmp_info.number_colors=0;
1616         bmp_info.bits_per_pixel=(unsigned short)
1617           ((type > 3) && (image->alpha_trait == BlendPixelTrait) ? 32 : 24);
1618         bmp_info.compression=(unsigned int) ((type > 3) &&
1619           (image->alpha_trait == BlendPixelTrait) ?  BI_BITFIELDS : BI_RGB);
1620       }
1621     bytes_per_line=4*((image->columns*bmp_info.bits_per_pixel+31)/32);
1622     bmp_info.ba_offset=0;
1623     profile=GetImageProfile(image,"icc");
1624     have_color_info=(image->rendering_intent != UndefinedIntent) ||
1625       (profile != (StringInfo *) NULL) || (image->gamma != 0.0) ?  MagickTrue :
1626       MagickFalse;
1627     if (type == 2)
1628       bmp_info.size=12;
1629     else
1630       if ((type == 3) || ((image->alpha_trait != BlendPixelTrait) &&
1631           (have_color_info == MagickFalse)))
1632         {
1633           type=3;
1634           bmp_info.size=40;
1635         }
1636       else
1637         {
1638           int
1639             extra_size;
1640
1641           bmp_info.size=108;
1642           extra_size=68;
1643           if ((image->rendering_intent != UndefinedIntent) ||
1644               (profile != (StringInfo *) NULL))
1645             {
1646               bmp_info.size=124;
1647               extra_size+=16;
1648             }
1649           bmp_info.file_size+=extra_size;
1650           bmp_info.offset_bits+=extra_size;
1651         }
1652     bmp_info.width=(ssize_t) image->columns;
1653     bmp_info.height=(ssize_t) image->rows;
1654     bmp_info.planes=1;
1655     bmp_info.image_size=(unsigned int) (bytes_per_line*image->rows);
1656     bmp_info.file_size+=bmp_info.image_size;
1657     bmp_info.x_pixels=75*39;
1658     bmp_info.y_pixels=75*39;
1659     switch (image->units)
1660     {
1661       case UndefinedResolution:
1662       case PixelsPerInchResolution:
1663       {
1664         bmp_info.x_pixels=(unsigned int) (100.0*image->resolution.x/2.54);
1665         bmp_info.y_pixels=(unsigned int) (100.0*image->resolution.y/2.54);
1666         break;
1667       }
1668       case PixelsPerCentimeterResolution:
1669       {
1670         bmp_info.x_pixels=(unsigned int) (100.0*image->resolution.x);
1671         bmp_info.y_pixels=(unsigned int) (100.0*image->resolution.y);
1672         break;
1673       }
1674     }
1675     bmp_info.colors_important=bmp_info.number_colors;
1676     /*
1677       Convert MIFF to BMP raster pixels.
1678     */
1679     pixel_info=AcquireVirtualMemory((size_t) bmp_info.image_size,
1680       sizeof(*pixels));
1681     if (pixel_info == (MemoryInfo *) NULL)
1682       ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed");
1683     pixels=(unsigned char *) GetVirtualMemoryBlob(pixel_info);
1684     (void) ResetMagickMemory(pixels,0,(size_t) bmp_info.image_size);
1685     switch (bmp_info.bits_per_pixel)
1686     {
1687       case 1:
1688       {
1689         size_t
1690           bit,
1691           byte;
1692
1693         /*
1694           Convert PseudoClass image to a BMP monochrome image.
1695         */
1696         for (y=0; y < (ssize_t) image->rows; y++)
1697         {
1698           ssize_t
1699             offset;
1700
1701           p=GetVirtualPixels(image,0,y,image->columns,1,exception);
1702           if (p == (const Quantum *) NULL)
1703             break;
1704           q=pixels+(image->rows-y-1)*bytes_per_line;
1705           bit=0;
1706           byte=0;
1707           for (x=0; x < (ssize_t) image->columns; x++)
1708           {
1709             byte<<=1;
1710             byte|=GetPixelIndex(image,p) != 0 ? 0x01 : 0x00;
1711             bit++;
1712             if (bit == 8)
1713               {
1714                 *q++=(unsigned char) byte;
1715                 bit=0;
1716                 byte=0;
1717               }
1718              p+=GetPixelChannels(image);
1719            }
1720            if (bit != 0)
1721              {
1722                *q++=(unsigned char) (byte << (8-bit));
1723                x++;
1724              }
1725           offset=(ssize_t) (image->columns+7)/8;
1726           for (x=offset; x < (ssize_t) bytes_per_line; x++)
1727             *q++=0x00;
1728           if (image->previous == (Image *) NULL)
1729             {
1730               status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y,
1731                 image->rows);
1732               if (status == MagickFalse)
1733                 break;
1734             }
1735         }
1736         break;
1737       }
1738       case 4:
1739       {
1740         size_t
1741           byte,
1742           nibble;
1743
1744         ssize_t
1745           offset;
1746
1747         /*
1748           Convert PseudoClass image to a BMP monochrome image.
1749         */
1750         for (y=0; y < (ssize_t) image->rows; y++)
1751         {
1752           p=GetVirtualPixels(image,0,y,image->columns,1,exception);
1753           if (p == (const Quantum *) NULL)
1754             break;
1755           q=pixels+(image->rows-y-1)*bytes_per_line;
1756           nibble=0;
1757           byte=0;
1758           for (x=0; x < (ssize_t) image->columns; x++)
1759           {
1760             byte<<=4;
1761             byte|=((size_t) GetPixelIndex(image,p) & 0x0f);
1762             nibble++;
1763             if (nibble == 2)
1764               {
1765                 *q++=(unsigned char) byte;
1766                 nibble=0;
1767                 byte=0;
1768               }
1769             p+=GetPixelChannels(image);
1770           }
1771           if (nibble != 0)
1772             {
1773               *q++=(unsigned char) (byte << 4);
1774               x++;
1775             }
1776           offset=(ssize_t) (image->columns+1)/2;
1777           for (x=offset; x < (ssize_t) bytes_per_line; x++)
1778             *q++=0x00;
1779           if (image->previous == (Image *) NULL)
1780             {
1781               status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y,
1782                 image->rows);
1783               if (status == MagickFalse)
1784                 break;
1785             }
1786         }
1787         break;
1788       }
1789       case 8:
1790       {
1791         /*
1792           Convert PseudoClass packet to BMP pixel.
1793         */
1794         for (y=0; y < (ssize_t) image->rows; y++)
1795         {
1796           p=GetVirtualPixels(image,0,y,image->columns,1,exception);
1797           if (p == (const Quantum *) NULL)
1798             break;
1799           q=pixels+(image->rows-y-1)*bytes_per_line;
1800           for (x=0; x < (ssize_t) image->columns; x++)
1801           {
1802             *q++=(unsigned char) GetPixelIndex(image,p);
1803             p+=GetPixelChannels(image);
1804           }
1805           for ( ; x < (ssize_t) bytes_per_line; x++)
1806             *q++=0x00;
1807           if (image->previous == (Image *) NULL)
1808             {
1809               status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y,
1810                 image->rows);
1811               if (status == MagickFalse)
1812                 break;
1813             }
1814         }
1815         break;
1816       }
1817       case 24:
1818       {
1819         /*
1820           Convert DirectClass packet to BMP BGR888.
1821         */
1822         for (y=0; y < (ssize_t) image->rows; y++)
1823         {
1824           p=GetVirtualPixels(image,0,y,image->columns,1,exception);
1825           if (p == (const Quantum *) NULL)
1826             break;
1827           q=pixels+(image->rows-y-1)*bytes_per_line;
1828           for (x=0; x < (ssize_t) image->columns; x++)
1829           {
1830             *q++=ScaleQuantumToChar(GetPixelBlue(image,p));
1831             *q++=ScaleQuantumToChar(GetPixelGreen(image,p));
1832             *q++=ScaleQuantumToChar(GetPixelRed(image,p));
1833             p+=GetPixelChannels(image);
1834           }
1835           for (x=3L*(ssize_t) image->columns; x < (ssize_t) bytes_per_line; x++)
1836             *q++=0x00;
1837           if (image->previous == (Image *) NULL)
1838             {
1839               status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y,
1840                 image->rows);
1841               if (status == MagickFalse)
1842                 break;
1843             }
1844         }
1845         break;
1846       }
1847       case 32:
1848       {
1849         /*
1850           Convert DirectClass packet to ARGB8888 pixel.
1851         */
1852         for (y=0; y < (ssize_t) image->rows; y++)
1853         {
1854           p=GetVirtualPixels(image,0,y,image->columns,1,exception);
1855           if (p == (const Quantum *) NULL)
1856             break;
1857           q=pixels+(image->rows-y-1)*bytes_per_line;
1858           for (x=0; x < (ssize_t) image->columns; x++)
1859           {
1860             *q++=ScaleQuantumToChar(GetPixelBlue(image,p));
1861             *q++=ScaleQuantumToChar(GetPixelGreen(image,p));
1862             *q++=ScaleQuantumToChar(GetPixelRed(image,p));
1863             *q++=ScaleQuantumToChar(GetPixelAlpha(image,p));
1864             p+=GetPixelChannels(image);
1865           }
1866           if (image->previous == (Image *) NULL)
1867             {
1868               status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y,
1869                 image->rows);
1870               if (status == MagickFalse)
1871                 break;
1872             }
1873         }
1874         break;
1875       }
1876     }
1877     if ((type > 2) && (bmp_info.bits_per_pixel == 8))
1878       if (image_info->compression != NoCompression)
1879         {
1880           MemoryInfo
1881             *rle_info;
1882
1883           /*
1884             Convert run-length encoded raster pixels.
1885           */
1886           rle_info=AcquireVirtualMemory((size_t) (2*(bytes_per_line+2)+2),
1887             (image->rows+2)*sizeof(*pixels));
1888           if (rle_info == (MemoryInfo *) NULL)
1889             {
1890               pixel_info=RelinquishVirtualMemory(pixel_info);
1891               ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed");
1892             }
1893           bmp_data=(unsigned char *) GetVirtualMemoryBlob(rle_info);
1894           bmp_info.file_size-=bmp_info.image_size;
1895           bmp_info.image_size=(unsigned int) EncodeImage(image,bytes_per_line,
1896             pixels,bmp_data);
1897           bmp_info.file_size+=bmp_info.image_size;
1898           pixel_info=RelinquishVirtualMemory(pixel_info);
1899           pixel_info=rle_info;
1900           pixels=bmp_data;
1901           bmp_info.compression=BI_RLE8;
1902         }
1903     /*
1904       Write BMP for Windows, all versions, 14-byte header.
1905     */
1906     if (image->debug != MagickFalse)
1907       {
1908         (void) LogMagickEvent(CoderEvent,GetMagickModule(),
1909           "   Writing BMP version %.20g datastream",(double) type);
1910         if (image->storage_class == DirectClass)
1911           (void) LogMagickEvent(CoderEvent,GetMagickModule(),
1912             "   Storage class=DirectClass");
1913         else
1914           (void) LogMagickEvent(CoderEvent,GetMagickModule(),
1915             "   Storage class=PseudoClass");
1916         (void) LogMagickEvent(CoderEvent,GetMagickModule(),
1917           "   Image depth=%.20g",(double) image->depth);
1918         if (image->alpha_trait == BlendPixelTrait)
1919           (void) LogMagickEvent(CoderEvent,GetMagickModule(),
1920             "   Matte=True");
1921         else
1922           (void) LogMagickEvent(CoderEvent,GetMagickModule(),
1923             "   Matte=MagickFalse");
1924         (void) LogMagickEvent(CoderEvent,GetMagickModule(),
1925           "   BMP bits_per_pixel=%.20g",(double) bmp_info.bits_per_pixel);
1926         switch ((int) bmp_info.compression)
1927         {
1928            case BI_RGB:
1929            {
1930              (void) LogMagickEvent(CoderEvent,GetMagickModule(),
1931                "   Compression=BI_RGB");
1932              break;
1933            }
1934            case BI_RLE8:
1935            {
1936              (void) LogMagickEvent(CoderEvent,GetMagickModule(),
1937                "   Compression=BI_RLE8");
1938              break;
1939            }
1940            case BI_BITFIELDS:
1941            {
1942              (void) LogMagickEvent(CoderEvent,GetMagickModule(),
1943                "   Compression=BI_BITFIELDS");
1944              break;
1945            }
1946            default:
1947            {
1948              (void) LogMagickEvent(CoderEvent,GetMagickModule(),
1949                "   Compression=UNKNOWN (%u)",bmp_info.compression);
1950              break;
1951            }
1952         }
1953         if (bmp_info.number_colors == 0)
1954           (void) LogMagickEvent(CoderEvent,GetMagickModule(),
1955             "   Number_colors=unspecified");
1956         else
1957           (void) LogMagickEvent(CoderEvent,GetMagickModule(),
1958             "   Number_colors=%u",bmp_info.number_colors);
1959       }
1960     (void) WriteBlob(image,2,(unsigned char *) "BM");
1961     (void) WriteBlobLSBLong(image,bmp_info.file_size);
1962     (void) WriteBlobLSBLong(image,bmp_info.ba_offset);  /* always 0 */
1963     (void) WriteBlobLSBLong(image,bmp_info.offset_bits);
1964     if (type == 2)
1965       {
1966         /*
1967           Write 12-byte version 2 bitmap header.
1968         */
1969         (void) WriteBlobLSBLong(image,bmp_info.size);
1970         (void) WriteBlobLSBShort(image,(unsigned short) bmp_info.width);
1971         (void) WriteBlobLSBShort(image,(unsigned short) bmp_info.height);
1972         (void) WriteBlobLSBShort(image,bmp_info.planes);
1973         (void) WriteBlobLSBShort(image,bmp_info.bits_per_pixel);
1974       }
1975     else
1976       {
1977         /*
1978           Write 40-byte version 3+ bitmap header.
1979         */
1980         (void) WriteBlobLSBLong(image,bmp_info.size);
1981         (void) WriteBlobLSBLong(image,(unsigned int) bmp_info.width);
1982         (void) WriteBlobLSBLong(image,(unsigned int) bmp_info.height);
1983         (void) WriteBlobLSBShort(image,bmp_info.planes);
1984         (void) WriteBlobLSBShort(image,bmp_info.bits_per_pixel);
1985         (void) WriteBlobLSBLong(image,bmp_info.compression);
1986         (void) WriteBlobLSBLong(image,bmp_info.image_size);
1987         (void) WriteBlobLSBLong(image,bmp_info.x_pixels);
1988         (void) WriteBlobLSBLong(image,bmp_info.y_pixels);
1989         (void) WriteBlobLSBLong(image,bmp_info.number_colors);
1990         (void) WriteBlobLSBLong(image,bmp_info.colors_important);
1991       }
1992     if ((type > 3) && ((image->alpha_trait == BlendPixelTrait) ||
1993         (have_color_info != MagickFalse)))
1994       {
1995         /*
1996           Write the rest of the 108-byte BMP Version 4 header.
1997         */
1998         (void) WriteBlobLSBLong(image,0x00ff0000U);  /* Red mask */
1999         (void) WriteBlobLSBLong(image,0x0000ff00U);  /* Green mask */
2000         (void) WriteBlobLSBLong(image,0x000000ffU);  /* Blue mask */
2001         (void) WriteBlobLSBLong(image,0xff000000U);  /* Alpha mask */
2002         (void) WriteBlobLSBLong(image,0x73524742U);  /* sRGB */
2003         (void) WriteBlobLSBLong(image,(unsigned int)
2004           (image->chromaticity.red_primary.x*0x40000000));
2005         (void) WriteBlobLSBLong(image,(unsigned int)
2006           (image->chromaticity.red_primary.y*0x40000000));
2007         (void) WriteBlobLSBLong(image,(unsigned int)
2008           ((1.000f-(image->chromaticity.red_primary.x+
2009           image->chromaticity.red_primary.y))*0x40000000));
2010         (void) WriteBlobLSBLong(image,(unsigned int)
2011           (image->chromaticity.green_primary.x*0x40000000));
2012         (void) WriteBlobLSBLong(image,(unsigned int)
2013           (image->chromaticity.green_primary.y*0x40000000));
2014         (void) WriteBlobLSBLong(image,(unsigned int)
2015           ((1.000f-(image->chromaticity.green_primary.x+
2016           image->chromaticity.green_primary.y))*0x40000000));
2017         (void) WriteBlobLSBLong(image,(unsigned int)
2018           (image->chromaticity.blue_primary.x*0x40000000));
2019         (void) WriteBlobLSBLong(image,(unsigned int)
2020           (image->chromaticity.blue_primary.y*0x40000000));
2021         (void) WriteBlobLSBLong(image,(unsigned int)
2022           ((1.000f-(image->chromaticity.blue_primary.x+
2023           image->chromaticity.blue_primary.y))*0x40000000));
2024         (void) WriteBlobLSBLong(image,(unsigned int)
2025           (bmp_info.gamma_scale.x*0x10000));
2026         (void) WriteBlobLSBLong(image,(unsigned int)
2027           (bmp_info.gamma_scale.y*0x10000));
2028         (void) WriteBlobLSBLong(image,(unsigned int)
2029           (bmp_info.gamma_scale.z*0x10000));
2030         if ((image->rendering_intent != UndefinedIntent) ||
2031             (profile != (StringInfo *) NULL))
2032           {
2033             ssize_t
2034               intent;
2035
2036             switch ((int) image->rendering_intent)
2037             {
2038               case SaturationIntent:
2039               {
2040                 intent=LCS_GM_BUSINESS;
2041                 break;
2042               }
2043               case RelativeIntent:
2044               {
2045                 intent=LCS_GM_GRAPHICS;
2046                 break;
2047               }
2048               case PerceptualIntent:
2049               {
2050                 intent=LCS_GM_IMAGES;
2051                 break;
2052               }
2053               case AbsoluteIntent:
2054               {
2055                 intent=LCS_GM_ABS_COLORIMETRIC;
2056                 break;
2057               }
2058               default:
2059               {
2060                 intent=0;
2061                 break;
2062               }
2063             }
2064             (void) WriteBlobLSBLong(image,(unsigned int) intent);
2065             (void) WriteBlobLSBLong(image,0x00);  /* dummy profile data */
2066             (void) WriteBlobLSBLong(image,0x00);  /* dummy profile length */
2067             (void) WriteBlobLSBLong(image,0x00);  /* reserved */
2068           }
2069       }
2070     if (image->storage_class == PseudoClass)
2071       {
2072         unsigned char
2073           *bmp_colormap;
2074
2075         /*
2076           Dump colormap to file.
2077         */
2078         if (image->debug != MagickFalse)
2079           (void) LogMagickEvent(CoderEvent,GetMagickModule(),
2080             "  Colormap: %.20g entries",(double) image->colors);
2081         bmp_colormap=(unsigned char *) AcquireQuantumMemory((size_t) (1UL <<
2082           bmp_info.bits_per_pixel),4*sizeof(*bmp_colormap));
2083         if (bmp_colormap == (unsigned char *) NULL)
2084           ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed");
2085         q=bmp_colormap;
2086         for (i=0; i < (ssize_t) MagickMin((ssize_t) image->colors,(ssize_t) bmp_info.number_colors); i++)
2087         {
2088           *q++=ScaleQuantumToChar(ClampToQuantum(image->colormap[i].blue));
2089           *q++=ScaleQuantumToChar(ClampToQuantum(image->colormap[i].green));
2090           *q++=ScaleQuantumToChar(ClampToQuantum(image->colormap[i].red));
2091           if (type > 2)
2092             *q++=(unsigned char) 0x0;
2093         }
2094         for ( ; i < (ssize_t) (1UL << bmp_info.bits_per_pixel); i++)
2095         {
2096           *q++=(unsigned char) 0x00;
2097           *q++=(unsigned char) 0x00;
2098           *q++=(unsigned char) 0x00;
2099           if (type > 2)
2100             *q++=(unsigned char) 0x00;
2101         }
2102         if (type <= 2)
2103           (void) WriteBlob(image,(size_t) (3*(1L << bmp_info.bits_per_pixel)),
2104             bmp_colormap);
2105         else
2106           (void) WriteBlob(image,(size_t) (4*(1L << bmp_info.bits_per_pixel)),
2107             bmp_colormap);
2108         bmp_colormap=(unsigned char *) RelinquishMagickMemory(bmp_colormap);
2109       }
2110     if (image->debug != MagickFalse)
2111       (void) LogMagickEvent(CoderEvent,GetMagickModule(),
2112         "  Pixels:  %u bytes",bmp_info.image_size);
2113     (void) WriteBlob(image,(size_t) bmp_info.image_size,pixels);
2114     pixel_info=RelinquishVirtualMemory(pixel_info);
2115     if (GetNextImageInList(image) == (Image *) NULL)
2116       break;
2117     image=SyncNextImageInList(image);
2118     status=SetImageProgress(image,SaveImagesTag,scene++,
2119       GetImageListLength(image));
2120     if (status == MagickFalse)
2121       break;
2122   } while (image_info->adjoin != MagickFalse);
2123   (void) CloseBlob(image);
2124   return(MagickTrue);
2125 }