• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * wrbmp.c
3  *
4  * This file was part of the Independent JPEG Group's software:
5  * Copyright (C) 1994-1996, Thomas G. Lane.
6  * libjpeg-turbo Modifications:
7  * Copyright (C) 2013, Linaro Limited.
8  * Copyright (C) 2014-2015, 2017, 2019, D. R. Commander.
9  * For conditions of distribution and use, see the accompanying README.ijg
10  * file.
11  *
12  * This file contains routines to write output images in Microsoft "BMP"
13  * format (MS Windows 3.x and OS/2 1.x flavors).
14  * Either 8-bit colormapped or 24-bit full-color format can be written.
15  * No compression is supported.
16  *
17  * These routines may need modification for non-Unix environments or
18  * specialized applications.  As they stand, they assume output to
19  * an ordinary stdio stream.
20  *
21  * This code contributed by James Arthur Boucher.
22  */
23 
24 #include "cmyk.h"
25 #include "cdjpeg.h"             /* Common decls for cjpeg/djpeg applications */
26 #include "jconfigint.h"
27 
28 #ifdef BMP_SUPPORTED
29 
30 
31 /*
32  * To support 12-bit JPEG data, we'd have to scale output down to 8 bits.
33  * This is not yet implemented.
34  */
35 
36 #if BITS_IN_JSAMPLE != 8
37   Sorry, this code only copes with 8-bit JSAMPLEs. /* deliberate syntax err */
38 #endif
39 
40 /*
41  * Since BMP stores scanlines bottom-to-top, we have to invert the image
42  * from JPEG's top-to-bottom order.  To do this, we save the outgoing data
43  * in a virtual array during put_pixel_row calls, then actually emit the
44  * BMP file during finish_output.  The virtual array contains one JSAMPLE per
45  * pixel if the output is grayscale or colormapped, three if it is full color.
46  */
47 
48 /* Private version of data destination object */
49 
50 typedef struct {
51   struct djpeg_dest_struct pub; /* public fields */
52 
53   boolean is_os2;               /* saves the OS2 format request flag */
54 
55   jvirt_sarray_ptr whole_image; /* needed to reverse row order */
56   JDIMENSION data_width;        /* JSAMPLEs per row */
57   JDIMENSION row_width;         /* physical width of one row in the BMP file */
58   int pad_bytes;                /* number of padding bytes needed per row */
59   JDIMENSION cur_output_row;    /* next row# to write to virtual array */
60 
61   boolean use_inversion_array;  /* TRUE = buffer the whole image, which is
62                                    stored to disk in bottom-up order, and
63                                    receive rows from the calling program in
64                                    top-down order
65 
66                                    FALSE = the calling program will maintain
67                                    its own image buffer and write the rows in
68                                    bottom-up order */
69 
70   JSAMPLE *iobuffer;            /* I/O buffer (used to buffer a single row to
71                                    disk if use_inversion_array == FALSE) */
72 } bmp_dest_struct;
73 
74 typedef bmp_dest_struct *bmp_dest_ptr;
75 
76 
77 /* Forward declarations */
78 LOCAL(void) write_colormap(j_decompress_ptr cinfo, bmp_dest_ptr dest,
79                            int map_colors, int map_entry_size);
80 
81 
is_big_endian(void)82 static INLINE boolean is_big_endian(void)
83 {
84   int test_value = 1;
85   if (*(char *)&test_value != 1)
86     return TRUE;
87   return FALSE;
88 }
89 
90 
91 /*
92  * Write some pixel data.
93  * In this module rows_supplied will always be 1.
94  */
95 
96 METHODDEF(void)
put_pixel_rows(j_decompress_ptr cinfo,djpeg_dest_ptr dinfo,JDIMENSION rows_supplied)97 put_pixel_rows(j_decompress_ptr cinfo, djpeg_dest_ptr dinfo,
98                JDIMENSION rows_supplied)
99 /* This version is for writing 24-bit pixels */
100 {
101   bmp_dest_ptr dest = (bmp_dest_ptr)dinfo;
102   JSAMPARRAY image_ptr;
103   register JSAMPROW inptr, outptr;
104   register JDIMENSION col;
105   int pad;
106 
107   if (dest->use_inversion_array) {
108     /* Access next row in virtual array */
109     image_ptr = (*cinfo->mem->access_virt_sarray)
110       ((j_common_ptr)cinfo, dest->whole_image,
111        dest->cur_output_row, (JDIMENSION)1, TRUE);
112     dest->cur_output_row++;
113     outptr = image_ptr[0];
114   } else {
115     outptr = dest->iobuffer;
116   }
117 
118   /* Transfer data.  Note destination values must be in BGR order
119    * (even though Microsoft's own documents say the opposite).
120    */
121   inptr = dest->pub.buffer[0];
122 
123   if (cinfo->out_color_space == JCS_EXT_BGR) {
124     MEMCOPY(outptr, inptr, dest->row_width);
125     outptr += cinfo->output_width * 3;
126   } else if (cinfo->out_color_space == JCS_RGB565) {
127     boolean big_endian = is_big_endian();
128     unsigned short *inptr2 = (unsigned short *)inptr;
129     for (col = cinfo->output_width; col > 0; col--) {
130       if (big_endian) {
131         outptr[0] = (*inptr2 >> 5) & 0xF8;
132         outptr[1] = ((*inptr2 << 5) & 0xE0) | ((*inptr2 >> 11) & 0x1C);
133         outptr[2] = *inptr2 & 0xF8;
134       } else {
135         outptr[0] = (*inptr2 << 3) & 0xF8;
136         outptr[1] = (*inptr2 >> 3) & 0xFC;
137         outptr[2] = (*inptr2 >> 8) & 0xF8;
138       }
139       outptr += 3;
140       inptr2++;
141     }
142   } else if (cinfo->out_color_space == JCS_CMYK) {
143     for (col = cinfo->output_width; col > 0; col--) {
144       JSAMPLE c = *inptr++, m = *inptr++, y = *inptr++, k = *inptr++;
145       cmyk_to_rgb(c, m, y, k, outptr + 2, outptr + 1, outptr);
146       outptr += 3;
147     }
148   } else {
149     register int rindex = rgb_red[cinfo->out_color_space];
150     register int gindex = rgb_green[cinfo->out_color_space];
151     register int bindex = rgb_blue[cinfo->out_color_space];
152     register int ps = rgb_pixelsize[cinfo->out_color_space];
153 
154     for (col = cinfo->output_width; col > 0; col--) {
155       outptr[0] = inptr[bindex];
156       outptr[1] = inptr[gindex];
157       outptr[2] = inptr[rindex];
158       outptr += 3;  inptr += ps;
159     }
160   }
161 
162   /* Zero out the pad bytes. */
163   pad = dest->pad_bytes;
164   while (--pad >= 0)
165     *outptr++ = 0;
166 
167   if (!dest->use_inversion_array)
168     (void)JFWRITE(dest->pub.output_file, dest->iobuffer, dest->row_width);
169 }
170 
171 METHODDEF(void)
put_gray_rows(j_decompress_ptr cinfo,djpeg_dest_ptr dinfo,JDIMENSION rows_supplied)172 put_gray_rows(j_decompress_ptr cinfo, djpeg_dest_ptr dinfo,
173               JDIMENSION rows_supplied)
174 /* This version is for grayscale OR quantized color output */
175 {
176   bmp_dest_ptr dest = (bmp_dest_ptr)dinfo;
177   JSAMPARRAY image_ptr;
178   register JSAMPROW inptr, outptr;
179   int pad;
180 
181   if (dest->use_inversion_array) {
182     /* Access next row in virtual array */
183     image_ptr = (*cinfo->mem->access_virt_sarray)
184       ((j_common_ptr)cinfo, dest->whole_image,
185        dest->cur_output_row, (JDIMENSION)1, TRUE);
186     dest->cur_output_row++;
187     outptr = image_ptr[0];
188   } else {
189     outptr = dest->iobuffer;
190   }
191 
192   /* Transfer data. */
193   inptr = dest->pub.buffer[0];
194   MEMCOPY(outptr, inptr, cinfo->output_width);
195   outptr += cinfo->output_width;
196 
197   /* Zero out the pad bytes. */
198   pad = dest->pad_bytes;
199   while (--pad >= 0)
200     *outptr++ = 0;
201 
202   if (!dest->use_inversion_array)
203     (void)JFWRITE(dest->pub.output_file, dest->iobuffer, dest->row_width);
204 }
205 
206 
207 /*
208  * Finish up at the end of the file.
209  *
210  * Here is where we really output the BMP file.
211  *
212  * First, routines to write the Windows and OS/2 variants of the file header.
213  */
214 
215 LOCAL(void)
write_bmp_header(j_decompress_ptr cinfo,bmp_dest_ptr dest)216 write_bmp_header(j_decompress_ptr cinfo, bmp_dest_ptr dest)
217 /* Write a Windows-style BMP file header, including colormap if needed */
218 {
219   char bmpfileheader[14];
220   char bmpinfoheader[40];
221 
222 #define PUT_2B(array, offset, value) \
223   (array[offset] = (char)((value) & 0xFF), \
224    array[offset + 1] = (char)(((value) >> 8) & 0xFF))
225 #define PUT_4B(array, offset, value) \
226   (array[offset] = (char)((value) & 0xFF), \
227    array[offset + 1] = (char)(((value) >> 8) & 0xFF), \
228    array[offset + 2] = (char)(((value) >> 16) & 0xFF), \
229    array[offset + 3] = (char)(((value) >> 24) & 0xFF))
230 
231   long headersize, bfSize;
232   int bits_per_pixel, cmap_entries;
233 
234   /* Compute colormap size and total file size */
235   if (IsExtRGB(cinfo->out_color_space)) {
236     if (cinfo->quantize_colors) {
237       /* Colormapped RGB */
238       bits_per_pixel = 8;
239       cmap_entries = 256;
240     } else {
241       /* Unquantized, full color RGB */
242       bits_per_pixel = 24;
243       cmap_entries = 0;
244     }
245   } else if (cinfo->out_color_space == JCS_RGB565 ||
246              cinfo->out_color_space == JCS_CMYK) {
247     bits_per_pixel = 24;
248     cmap_entries   = 0;
249   } else {
250     /* Grayscale output.  We need to fake a 256-entry colormap. */
251     bits_per_pixel = 8;
252     cmap_entries = 256;
253   }
254   /* File size */
255   headersize = 14 + 40 + cmap_entries * 4; /* Header and colormap */
256   bfSize = headersize + (long)dest->row_width * (long)cinfo->output_height;
257 
258   /* Set unused fields of header to 0 */
259   MEMZERO(bmpfileheader, sizeof(bmpfileheader));
260   MEMZERO(bmpinfoheader, sizeof(bmpinfoheader));
261 
262   /* Fill the file header */
263   bmpfileheader[0] = 0x42;      /* first 2 bytes are ASCII 'B', 'M' */
264   bmpfileheader[1] = 0x4D;
265   PUT_4B(bmpfileheader, 2, bfSize); /* bfSize */
266   /* we leave bfReserved1 & bfReserved2 = 0 */
267   PUT_4B(bmpfileheader, 10, headersize); /* bfOffBits */
268 
269   /* Fill the info header (Microsoft calls this a BITMAPINFOHEADER) */
270   PUT_2B(bmpinfoheader, 0, 40); /* biSize */
271   PUT_4B(bmpinfoheader, 4, cinfo->output_width); /* biWidth */
272   PUT_4B(bmpinfoheader, 8, cinfo->output_height); /* biHeight */
273   PUT_2B(bmpinfoheader, 12, 1); /* biPlanes - must be 1 */
274   PUT_2B(bmpinfoheader, 14, bits_per_pixel); /* biBitCount */
275   /* we leave biCompression = 0, for none */
276   /* we leave biSizeImage = 0; this is correct for uncompressed data */
277   if (cinfo->density_unit == 2) { /* if have density in dots/cm, then */
278     PUT_4B(bmpinfoheader, 24, (long)(cinfo->X_density * 100)); /* XPels/M */
279     PUT_4B(bmpinfoheader, 28, (long)(cinfo->Y_density * 100)); /* XPels/M */
280   }
281   PUT_2B(bmpinfoheader, 32, cmap_entries); /* biClrUsed */
282   /* we leave biClrImportant = 0 */
283 
284   if (JFWRITE(dest->pub.output_file, bmpfileheader, 14) != (size_t)14)
285     ERREXIT(cinfo, JERR_FILE_WRITE);
286   if (JFWRITE(dest->pub.output_file, bmpinfoheader, 40) != (size_t)40)
287     ERREXIT(cinfo, JERR_FILE_WRITE);
288 
289   if (cmap_entries > 0)
290     write_colormap(cinfo, dest, cmap_entries, 4);
291 }
292 
293 
294 LOCAL(void)
write_os2_header(j_decompress_ptr cinfo,bmp_dest_ptr dest)295 write_os2_header(j_decompress_ptr cinfo, bmp_dest_ptr dest)
296 /* Write an OS2-style BMP file header, including colormap if needed */
297 {
298   char bmpfileheader[14];
299   char bmpcoreheader[12];
300   long headersize, bfSize;
301   int bits_per_pixel, cmap_entries;
302 
303   /* Compute colormap size and total file size */
304   if (IsExtRGB(cinfo->out_color_space)) {
305     if (cinfo->quantize_colors) {
306       /* Colormapped RGB */
307       bits_per_pixel = 8;
308       cmap_entries = 256;
309     } else {
310       /* Unquantized, full color RGB */
311       bits_per_pixel = 24;
312       cmap_entries = 0;
313     }
314   } else if (cinfo->out_color_space == JCS_RGB565 ||
315              cinfo->out_color_space == JCS_CMYK) {
316     bits_per_pixel = 24;
317     cmap_entries   = 0;
318   } else {
319     /* Grayscale output.  We need to fake a 256-entry colormap. */
320     bits_per_pixel = 8;
321     cmap_entries = 256;
322   }
323   /* File size */
324   headersize = 14 + 12 + cmap_entries * 3; /* Header and colormap */
325   bfSize = headersize + (long)dest->row_width * (long)cinfo->output_height;
326 
327   /* Set unused fields of header to 0 */
328   MEMZERO(bmpfileheader, sizeof(bmpfileheader));
329   MEMZERO(bmpcoreheader, sizeof(bmpcoreheader));
330 
331   /* Fill the file header */
332   bmpfileheader[0] = 0x42;      /* first 2 bytes are ASCII 'B', 'M' */
333   bmpfileheader[1] = 0x4D;
334   PUT_4B(bmpfileheader, 2, bfSize); /* bfSize */
335   /* we leave bfReserved1 & bfReserved2 = 0 */
336   PUT_4B(bmpfileheader, 10, headersize); /* bfOffBits */
337 
338   /* Fill the info header (Microsoft calls this a BITMAPCOREHEADER) */
339   PUT_2B(bmpcoreheader, 0, 12); /* bcSize */
340   PUT_2B(bmpcoreheader, 4, cinfo->output_width); /* bcWidth */
341   PUT_2B(bmpcoreheader, 6, cinfo->output_height); /* bcHeight */
342   PUT_2B(bmpcoreheader, 8, 1);  /* bcPlanes - must be 1 */
343   PUT_2B(bmpcoreheader, 10, bits_per_pixel); /* bcBitCount */
344 
345   if (JFWRITE(dest->pub.output_file, bmpfileheader, 14) != (size_t)14)
346     ERREXIT(cinfo, JERR_FILE_WRITE);
347   if (JFWRITE(dest->pub.output_file, bmpcoreheader, 12) != (size_t)12)
348     ERREXIT(cinfo, JERR_FILE_WRITE);
349 
350   if (cmap_entries > 0)
351     write_colormap(cinfo, dest, cmap_entries, 3);
352 }
353 
354 
355 /*
356  * Write the colormap.
357  * Windows uses BGR0 map entries; OS/2 uses BGR entries.
358  */
359 
360 LOCAL(void)
write_colormap(j_decompress_ptr cinfo,bmp_dest_ptr dest,int map_colors,int map_entry_size)361 write_colormap(j_decompress_ptr cinfo, bmp_dest_ptr dest, int map_colors,
362                int map_entry_size)
363 {
364   JSAMPARRAY colormap = cinfo->colormap;
365   int num_colors = cinfo->actual_number_of_colors;
366   FILE *outfile = dest->pub.output_file;
367   int i;
368 
369   if (colormap != NULL) {
370     if (cinfo->out_color_components == 3) {
371       /* Normal case with RGB colormap */
372       for (i = 0; i < num_colors; i++) {
373         putc(colormap[2][i], outfile);
374         putc(colormap[1][i], outfile);
375         putc(colormap[0][i], outfile);
376         if (map_entry_size == 4)
377           putc(0, outfile);
378       }
379     } else {
380       /* Grayscale colormap (only happens with grayscale quantization) */
381       for (i = 0; i < num_colors; i++) {
382         putc(colormap[0][i], outfile);
383         putc(colormap[0][i], outfile);
384         putc(colormap[0][i], outfile);
385         if (map_entry_size == 4)
386           putc(0, outfile);
387       }
388     }
389   } else {
390     /* If no colormap, must be grayscale data.  Generate a linear "map". */
391     for (i = 0; i < 256; i++) {
392       putc(i, outfile);
393       putc(i, outfile);
394       putc(i, outfile);
395       if (map_entry_size == 4)
396         putc(0, outfile);
397     }
398   }
399   /* Pad colormap with zeros to ensure specified number of colormap entries */
400   if (i > map_colors)
401     ERREXIT1(cinfo, JERR_TOO_MANY_COLORS, i);
402   for (; i < map_colors; i++) {
403     putc(0, outfile);
404     putc(0, outfile);
405     putc(0, outfile);
406     if (map_entry_size == 4)
407       putc(0, outfile);
408   }
409 }
410 
411 
412 /*
413  * Startup: write the file header unless the inversion array is being used.
414  */
415 
416 METHODDEF(void)
start_output_bmp(j_decompress_ptr cinfo,djpeg_dest_ptr dinfo)417 start_output_bmp(j_decompress_ptr cinfo, djpeg_dest_ptr dinfo)
418 {
419   bmp_dest_ptr dest = (bmp_dest_ptr)dinfo;
420 
421   if (!dest->use_inversion_array) {
422     /* Write the header and colormap */
423     if (dest->is_os2)
424       write_os2_header(cinfo, dest);
425     else
426       write_bmp_header(cinfo, dest);
427   }
428 }
429 
430 
431 METHODDEF(void)
finish_output_bmp(j_decompress_ptr cinfo,djpeg_dest_ptr dinfo)432 finish_output_bmp(j_decompress_ptr cinfo, djpeg_dest_ptr dinfo)
433 {
434   bmp_dest_ptr dest = (bmp_dest_ptr)dinfo;
435   register FILE *outfile = dest->pub.output_file;
436   JSAMPARRAY image_ptr;
437   register JSAMPROW data_ptr;
438   JDIMENSION row;
439   cd_progress_ptr progress = (cd_progress_ptr)cinfo->progress;
440 
441   if (dest->use_inversion_array) {
442     /* Write the header and colormap */
443     if (dest->is_os2)
444       write_os2_header(cinfo, dest);
445     else
446       write_bmp_header(cinfo, dest);
447 
448     /* Write the file body from our virtual array */
449     for (row = cinfo->output_height; row > 0; row--) {
450       if (progress != NULL) {
451         progress->pub.pass_counter = (long)(cinfo->output_height - row);
452         progress->pub.pass_limit = (long)cinfo->output_height;
453         (*progress->pub.progress_monitor) ((j_common_ptr)cinfo);
454       }
455       image_ptr = (*cinfo->mem->access_virt_sarray)
456         ((j_common_ptr)cinfo, dest->whole_image, row - 1, (JDIMENSION)1,
457          FALSE);
458       data_ptr = image_ptr[0];
459       (void)JFWRITE(outfile, data_ptr, dest->row_width);
460     }
461     if (progress != NULL)
462       progress->completed_extra_passes++;
463   }
464 
465   /* Make sure we wrote the output file OK */
466   fflush(outfile);
467   if (ferror(outfile))
468     ERREXIT(cinfo, JERR_FILE_WRITE);
469 }
470 
471 
472 /*
473  * The module selection routine for BMP format output.
474  */
475 
476 GLOBAL(djpeg_dest_ptr)
jinit_write_bmp(j_decompress_ptr cinfo,boolean is_os2,boolean use_inversion_array)477 jinit_write_bmp(j_decompress_ptr cinfo, boolean is_os2,
478                 boolean use_inversion_array)
479 {
480   bmp_dest_ptr dest;
481   JDIMENSION row_width;
482 
483   /* Create module interface object, fill in method pointers */
484   dest = (bmp_dest_ptr)
485     (*cinfo->mem->alloc_small) ((j_common_ptr)cinfo, JPOOL_IMAGE,
486                                 sizeof(bmp_dest_struct));
487   dest->pub.start_output = start_output_bmp;
488   dest->pub.finish_output = finish_output_bmp;
489   dest->pub.calc_buffer_dimensions = NULL;
490   dest->is_os2 = is_os2;
491 
492   if (cinfo->out_color_space == JCS_GRAYSCALE) {
493     dest->pub.put_pixel_rows = put_gray_rows;
494   } else if (IsExtRGB(cinfo->out_color_space)) {
495     if (cinfo->quantize_colors)
496       dest->pub.put_pixel_rows = put_gray_rows;
497     else
498       dest->pub.put_pixel_rows = put_pixel_rows;
499   } else if (!cinfo->quantize_colors &&
500              (cinfo->out_color_space == JCS_RGB565 ||
501               cinfo->out_color_space == JCS_CMYK)) {
502     dest->pub.put_pixel_rows = put_pixel_rows;
503   } else {
504     ERREXIT(cinfo, JERR_BMP_COLORSPACE);
505   }
506 
507   /* Calculate output image dimensions so we can allocate space */
508   jpeg_calc_output_dimensions(cinfo);
509 
510   /* Determine width of rows in the BMP file (padded to 4-byte boundary). */
511   if (cinfo->out_color_space == JCS_RGB565) {
512     row_width = cinfo->output_width * 2;
513     dest->row_width = dest->data_width = cinfo->output_width * 3;
514     while ((row_width & 3) != 0) row_width++;
515   } else if (!cinfo->quantize_colors &&
516              (IsExtRGB(cinfo->out_color_space) ||
517               cinfo->out_color_space == JCS_CMYK)) {
518     row_width = cinfo->output_width * cinfo->output_components;
519     dest->row_width = dest->data_width = cinfo->output_width * 3;
520   } else {
521     row_width = cinfo->output_width * cinfo->output_components;
522     dest->row_width = dest->data_width = row_width;
523   }
524   while ((dest->row_width & 3) != 0) dest->row_width++;
525   dest->pad_bytes = (int)(dest->row_width - dest->data_width);
526 
527 
528   if (use_inversion_array) {
529     /* Allocate space for inversion array, prepare for write pass */
530     dest->whole_image = (*cinfo->mem->request_virt_sarray)
531       ((j_common_ptr)cinfo, JPOOL_IMAGE, FALSE,
532        dest->row_width, cinfo->output_height, (JDIMENSION)1);
533     dest->cur_output_row = 0;
534     if (cinfo->progress != NULL) {
535       cd_progress_ptr progress = (cd_progress_ptr)cinfo->progress;
536       progress->total_extra_passes++; /* count file input as separate pass */
537     }
538   } else {
539     dest->iobuffer = (JSAMPLE *)(*cinfo->mem->alloc_small)
540       ((j_common_ptr)cinfo, JPOOL_IMAGE, dest->row_width);
541   }
542   dest->use_inversion_array = use_inversion_array;
543 
544   /* Create decompressor output buffer. */
545   dest->pub.buffer = (*cinfo->mem->alloc_sarray)
546     ((j_common_ptr)cinfo, JPOOL_IMAGE, row_width, (JDIMENSION)1);
547   dest->pub.buffer_height = 1;
548 
549   return (djpeg_dest_ptr)dest;
550 }
551 
552 #endif /* BMP_SUPPORTED */
553