1 /* $Id: bmp2tiff.c,v 1.23 2010-03-10 18:56:49 bfriesen Exp $
3 * Project: libtiff tools
4 * Purpose: Convert Windows BMP files in TIFF.
5 * Author: Andrey Kiselev, dron@ak4719.spb.edu
7 ******************************************************************************
8 * Copyright (c) 2004, Andrey Kiselev <dron@ak4719.spb.edu>
10 * Permission to use, copy, modify, distribute, and sell this software and
11 * its documentation for any purpose is hereby granted without fee, provided
12 * that (i) the above copyright notices and this permission notice appear in
13 * all copies of the software and related documentation, and (ii) the names of
14 * Sam Leffler and Silicon Graphics may not be used in any advertising or
15 * publicity relating to the software without the specific, prior written
16 * permission of Sam Leffler and Silicon Graphics.
18 * THE SOFTWARE IS PROVIDED "AS-IS" AND WITHOUT WARRANTY OF ANY KIND,
19 * EXPRESS, IMPLIED OR OTHERWISE, INCLUDING WITHOUT LIMITATION, ANY
20 * WARRANTY OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE.
22 * IN NO EVENT SHALL SAM LEFFLER OR SILICON GRAPHICS BE LIABLE FOR
23 * ANY SPECIAL, INCIDENTAL, INDIRECT OR CONSEQUENTIAL DAMAGES OF ANY KIND,
24 * OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS,
25 * WHETHER OR NOT ADVISED OF THE POSSIBILITY OF DAMAGE, AND ON ANY THEORY OF
26 * LIABILITY, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE
30 #include "tif_config.h"
36 #include <sys/types.h>
48 # include <sys/types.h>
67 BMPT_WIN4, /* BMP used in Windows 3.0/NT 3.51/95 */
68 BMPT_WIN5, /* BMP used in Windows NT 4.0/98/Me/2000/XP */
69 BMPT_OS21, /* BMP used in OS/2 PM 1.x */
70 BMPT_OS22 /* BMP used in OS/2 PM 2.x */
74 * Bitmap file consists of a BMPFileHeader structure followed by a
75 * BMPInfoHeader structure. An array of BMPColorEntry structures (also called
76 * a colour table) follows the bitmap information header structure. The colour
77 * table is followed by a second array of indexes into the colour table (the
78 * actual bitmap data). Data may be comressed, for 4-bpp and 8-bpp used RLE
81 * +---------------------+
83 * +---------------------+
85 * +---------------------+
86 * | BMPColorEntry array |
87 * +---------------------+
88 * | Colour-index array |
89 * +---------------------+
91 * All numbers stored in Intel order with least significant byte first.
96 BMPC_RGB = 0L, /* Uncompressed */
97 BMPC_RLE8 = 1L, /* RLE for 8 bpp images */
98 BMPC_RLE4 = 2L, /* RLE for 4 bpp images */
99 BMPC_BITFIELDS = 3L, /* Bitmap is not compressed and the colour table
100 * consists of three DWORD color masks that specify
101 * the red, green, and blue components of each
102 * pixel. This is valid when used with
103 * 16- and 32-bpp bitmaps. */
104 BMPC_JPEG = 4L, /* Indicates that the image is a JPEG image. */
105 BMPC_PNG = 5L /* Indicates that the image is a PNG image. */
108 enum BMPLCSType /* Type of logical color space. */
110 BMPLT_CALIBRATED_RGB = 0, /* This value indicates that endpoints and
111 * gamma values are given in the appropriate
113 BMPLT_DEVICE_RGB = 1,
114 BMPLT_DEVICE_CMYK = 2
124 typedef struct /* This structure contains the x, y, and z */
125 { /* coordinates of the three colors that */
127 BMPCIEXYZ iCIERed; /* to the red, green, and blue endpoints for */
128 BMPCIEXYZ iCIEGreen; /* a specified logical color space. */
134 char bType[2]; /* Signature "BM" */
135 uint32 iSize; /* Size in bytes of the bitmap file. Should
136 * always be ignored while reading because
137 * of error in Windows 3.0 SDK's description
139 uint16 iReserved1; /* Reserved, set as 0 */
140 uint16 iReserved2; /* Reserved, set as 0 */
141 uint32 iOffBits; /* Offset of the image from file start in bytes */
144 /* File header size in bytes: */
145 const int BFH_SIZE = 14;
149 uint32 iSize; /* Size of BMPInfoHeader structure in bytes.
150 * Should be used to determine start of the
152 int32 iWidth; /* Image width */
153 int32 iHeight; /* Image height. If positive, image has bottom
154 * left origin, if negative --- top left. */
155 int16 iPlanes; /* Number of image planes (must be set to 1) */
156 int16 iBitCount; /* Number of bits per pixel (1, 4, 8, 16, 24
157 * or 32). If 0 then the number of bits per
158 * pixel is specified or is implied by the
159 * JPEG or PNG format. */
160 uint32 iCompression; /* Compression method */
161 uint32 iSizeImage; /* Size of uncomressed image in bytes. May
162 * be 0 for BMPC_RGB bitmaps. If iCompression
163 * is BI_JPEG or BI_PNG, iSizeImage indicates
164 * the size of the JPEG or PNG image buffer. */
165 int32 iXPelsPerMeter; /* X resolution, pixels per meter (0 if not used) */
166 int32 iYPelsPerMeter; /* Y resolution, pixels per meter (0 if not used) */
167 uint32 iClrUsed; /* Size of colour table. If 0, iBitCount should
168 * be used to calculate this value
169 * (1<<iBitCount). This value should be
170 * unsigned for proper shifting. */
171 int32 iClrImportant; /* Number of important colours. If 0, all
172 * colours are required */
175 * Fields above should be used for bitmaps, compatible with Windows NT 3.51
176 * and earlier. Windows 98/Me, Windows 2000/XP introduces additional fields:
179 int32 iRedMask; /* Colour mask that specifies the red component
180 * of each pixel, valid only if iCompression
181 * is set to BI_BITFIELDS. */
182 int32 iGreenMask; /* The same for green component */
183 int32 iBlueMask; /* The same for blue component */
184 int32 iAlphaMask; /* Colour mask that specifies the alpha
185 * component of each pixel. */
186 uint32 iCSType; /* Colour space of the DIB. */
187 BMPCIEXYZTriple sEndpoints; /* This member is ignored unless the iCSType
188 * member specifies BMPLT_CALIBRATED_RGB. */
189 int32 iGammaRed; /* Toned response curve for red. This member
190 * is ignored unless color values are
191 * calibrated RGB values and iCSType is set to
192 * BMPLT_CALIBRATED_RGB. Specified
193 * in 16^16 format. */
194 int32 iGammaGreen; /* Toned response curve for green. */
195 int32 iGammaBlue; /* Toned response curve for blue. */
199 * Info header size in bytes:
201 const unsigned int BIH_WIN4SIZE = 40; /* for BMPT_WIN4 */
202 const unsigned int BIH_WIN5SIZE = 57; /* for BMPT_WIN5 */
203 const unsigned int BIH_OS21SIZE = 12; /* for BMPT_OS21 */
204 const unsigned int BIH_OS22SIZE = 64; /* for BMPT_OS22 */
207 * We will use plain byte array instead of this structure, but declaration
208 * provided for reference
215 char bReserved; /* Must be 0 */
218 static uint16 compression = (uint16) -1;
219 static int jpegcolormode = JPEGCOLORMODE_RGB;
220 static int quality = 75; /* JPEG quality */
221 static uint16 predictor = 0;
223 static void usage(void);
224 static int processCompressOptions(char*);
225 static void rearrangePixels(char *, uint32, uint32);
228 main(int argc, char* argv[])
230 uint32 width, length;
231 uint16 nbands = 1; /* number of bands in input image */
232 uint16 depth = 8; /* bits per pixel in input image */
233 uint32 rowsperstrip = (uint32) -1;
234 uint16 photometric = PHOTOMETRIC_MINISBLACK;
237 char *outfilename = NULL, *infilename = NULL;
240 BMPFileHeader file_hdr;
241 BMPInfoHeader info_hdr;
243 uint32 clr_tbl_size, n_clr_elems = 3;
244 unsigned char *clr_tbl;
245 unsigned short *red_tbl = NULL, *green_tbl = NULL, *blue_tbl = NULL;
252 while ((c = getopt(argc, argv, "c:r:o:h")) != -1) {
254 case 'c': /* compression scheme */
255 if (!processCompressOptions(optarg))
258 case 'r': /* rows/strip */
259 rowsperstrip = atoi(optarg);
262 outfilename = optarg;
271 if (argc - optind < 2)
274 if (outfilename == NULL)
275 outfilename = argv[argc-1];
276 out = TIFFOpen(outfilename, "w");
278 TIFFError(infilename, "Cannot open file %s for output",
284 while (optind < argc-1) {
285 infilename = argv[optind];
288 fd = open(infilename, O_RDONLY|O_BINARY, 0);
290 TIFFError(infilename, "Cannot open input file");
294 read(fd, file_hdr.bType, 2);
295 if(file_hdr.bType[0] != 'B' || file_hdr.bType[1] != 'M') {
296 TIFFError(infilename, "File is not BMP");
300 /* -------------------------------------------------------------------- */
301 /* Read the BMPFileHeader. We need iOffBits value only */
302 /* -------------------------------------------------------------------- */
303 lseek(fd, 10, SEEK_SET);
304 read(fd, &file_hdr.iOffBits, 4);
305 #ifdef WORDS_BIGENDIAN
306 TIFFSwabLong(&file_hdr.iOffBits);
309 file_hdr.iSize = instat.st_size;
311 /* -------------------------------------------------------------------- */
312 /* Read the BMPInfoHeader. */
313 /* -------------------------------------------------------------------- */
315 lseek(fd, BFH_SIZE, SEEK_SET);
316 read(fd, &info_hdr.iSize, 4);
317 #ifdef WORDS_BIGENDIAN
318 TIFFSwabLong(&info_hdr.iSize);
321 if (info_hdr.iSize == BIH_WIN4SIZE)
322 bmp_type = BMPT_WIN4;
323 else if (info_hdr.iSize == BIH_OS21SIZE)
324 bmp_type = BMPT_OS21;
325 else if (info_hdr.iSize == BIH_OS22SIZE
326 || info_hdr.iSize == 16)
327 bmp_type = BMPT_OS22;
329 bmp_type = BMPT_WIN5;
331 if (bmp_type == BMPT_WIN4
332 || bmp_type == BMPT_WIN5
333 || bmp_type == BMPT_OS22) {
334 read(fd, &info_hdr.iWidth, 4);
335 read(fd, &info_hdr.iHeight, 4);
336 read(fd, &info_hdr.iPlanes, 2);
337 read(fd, &info_hdr.iBitCount, 2);
338 read(fd, &info_hdr.iCompression, 4);
339 read(fd, &info_hdr.iSizeImage, 4);
340 read(fd, &info_hdr.iXPelsPerMeter, 4);
341 read(fd, &info_hdr.iYPelsPerMeter, 4);
342 read(fd, &info_hdr.iClrUsed, 4);
343 read(fd, &info_hdr.iClrImportant, 4);
344 #ifdef WORDS_BIGENDIAN
345 TIFFSwabLong((uint32*) &info_hdr.iWidth);
346 TIFFSwabLong((uint32*) &info_hdr.iHeight);
347 TIFFSwabShort((uint16*) &info_hdr.iPlanes);
348 TIFFSwabShort((uint16*) &info_hdr.iBitCount);
349 TIFFSwabLong((uint32*) &info_hdr.iCompression);
350 TIFFSwabLong((uint32*) &info_hdr.iSizeImage);
351 TIFFSwabLong((uint32*) &info_hdr.iXPelsPerMeter);
352 TIFFSwabLong((uint32*) &info_hdr.iYPelsPerMeter);
353 TIFFSwabLong((uint32*) &info_hdr.iClrUsed);
354 TIFFSwabLong((uint32*) &info_hdr.iClrImportant);
359 if (bmp_type == BMPT_OS22) {
361 * FIXME: different info in different documents
367 if (bmp_type == BMPT_OS21) {
370 read(fd, &iShort, 2);
371 #ifdef WORDS_BIGENDIAN
372 TIFFSwabShort((uint16*) &iShort);
374 info_hdr.iWidth = iShort;
375 read(fd, &iShort, 2);
376 #ifdef WORDS_BIGENDIAN
377 TIFFSwabShort((uint16*) &iShort);
379 info_hdr.iHeight = iShort;
380 read(fd, &iShort, 2);
381 #ifdef WORDS_BIGENDIAN
382 TIFFSwabShort((uint16*) &iShort);
384 info_hdr.iPlanes = iShort;
385 read(fd, &iShort, 2);
386 #ifdef WORDS_BIGENDIAN
387 TIFFSwabShort((uint16*) &iShort);
389 info_hdr.iBitCount = iShort;
390 info_hdr.iCompression = BMPC_RGB;
394 if (info_hdr.iBitCount != 1 && info_hdr.iBitCount != 4 &&
395 info_hdr.iBitCount != 8 && info_hdr.iBitCount != 16 &&
396 info_hdr.iBitCount != 24 && info_hdr.iBitCount != 32) {
397 TIFFError(infilename,
398 "Cannot process BMP file with bit count %d",
404 width = info_hdr.iWidth;
405 length = (info_hdr.iHeight > 0) ? info_hdr.iHeight : -info_hdr.iHeight;
407 switch (info_hdr.iBitCount)
413 depth = info_hdr.iBitCount;
414 photometric = PHOTOMETRIC_PALETTE;
415 /* Allocate memory for colour table and read it. */
416 if (info_hdr.iClrUsed)
418 ((uint32)(1<<depth)<info_hdr.iClrUsed)
419 ? (uint32) (1 << depth)
422 clr_tbl_size = 1 << depth;
423 clr_tbl = (unsigned char *)
424 _TIFFmalloc(n_clr_elems * clr_tbl_size);
426 TIFFError(infilename,
427 "Can't allocate space for color table");
431 lseek(fd, BFH_SIZE + info_hdr.iSize, SEEK_SET);
432 read(fd, clr_tbl, n_clr_elems * clr_tbl_size);
434 red_tbl = (unsigned short*)
435 _TIFFmalloc(((tmsize_t)1)<<depth * sizeof(unsigned short));
437 TIFFError(infilename,
438 "Can't allocate space for red component table");
442 green_tbl = (unsigned short*)
443 _TIFFmalloc(((tmsize_t)1)<<depth * sizeof(unsigned short));
445 TIFFError(infilename,
446 "Can't allocate space for green component table");
450 blue_tbl = (unsigned short*)
451 _TIFFmalloc(((tmsize_t)1)<<depth * sizeof(unsigned short));
453 TIFFError(infilename,
454 "Can't allocate space for blue component table");
459 for(clr = 0; clr < clr_tbl_size; clr++) {
460 red_tbl[clr] = 257*clr_tbl[clr*n_clr_elems+2];
461 green_tbl[clr] = 257*clr_tbl[clr*n_clr_elems+1];
462 blue_tbl[clr] = 257*clr_tbl[clr*n_clr_elems];
470 depth = info_hdr.iBitCount / nbands;
471 photometric = PHOTOMETRIC_RGB;
476 photometric = PHOTOMETRIC_RGB;
482 /* -------------------------------------------------------------------- */
483 /* Create output file. */
484 /* -------------------------------------------------------------------- */
486 TIFFSetField(out, TIFFTAG_IMAGEWIDTH, width);
487 TIFFSetField(out, TIFFTAG_IMAGELENGTH, length);
488 TIFFSetField(out, TIFFTAG_ORIENTATION, ORIENTATION_TOPLEFT);
489 TIFFSetField(out, TIFFTAG_SAMPLESPERPIXEL, nbands);
490 TIFFSetField(out, TIFFTAG_BITSPERSAMPLE, depth);
491 TIFFSetField(out, TIFFTAG_PLANARCONFIG, PLANARCONFIG_CONTIG);
492 TIFFSetField(out, TIFFTAG_PHOTOMETRIC, photometric);
493 TIFFSetField(out, TIFFTAG_ROWSPERSTRIP,
494 TIFFDefaultStripSize(out, rowsperstrip));
496 if (red_tbl && green_tbl && blue_tbl) {
497 TIFFSetField(out, TIFFTAG_COLORMAP,
498 red_tbl, green_tbl, blue_tbl);
501 if (compression == (uint16) -1)
502 compression = COMPRESSION_PACKBITS;
503 TIFFSetField(out, TIFFTAG_COMPRESSION, compression);
504 switch (compression) {
505 case COMPRESSION_JPEG:
506 if (photometric == PHOTOMETRIC_RGB
507 && jpegcolormode == JPEGCOLORMODE_RGB)
508 photometric = PHOTOMETRIC_YCBCR;
509 TIFFSetField(out, TIFFTAG_JPEGQUALITY, quality);
510 TIFFSetField(out, TIFFTAG_JPEGCOLORMODE, jpegcolormode);
512 case COMPRESSION_LZW:
513 case COMPRESSION_DEFLATE:
515 TIFFSetField(out, TIFFTAG_PREDICTOR, predictor);
519 /* -------------------------------------------------------------------- */
520 /* Read uncompressed image data. */
521 /* -------------------------------------------------------------------- */
523 if (info_hdr.iCompression == BMPC_RGB) {
527 /* XXX: Avoid integer overflow. We can calculate size
530 * size = ((width * info_hdr.iBitCount + 31) & ~31) / 8
532 * formulae, but we should check for overflow
533 * conditions during calculation.
535 size = width * info_hdr.iBitCount + 31;
536 if (!width || !info_hdr.iBitCount
537 || (size - 31) / info_hdr.iBitCount != width ) {
538 TIFFError(infilename,
539 "Wrong image parameters; can't "
540 "allocate space for scanline buffer");
543 size = (size & ~31) / 8;
545 scanbuf = (char *) _TIFFmalloc(size);
547 TIFFError(infilename,
548 "Can't allocate space for scanline buffer");
552 for (row = 0; row < length; row++) {
553 if (info_hdr.iHeight > 0)
554 offset = file_hdr.iOffBits+(length-row-1)*size;
556 offset = file_hdr.iOffBits + row * size;
557 if (lseek(fd, offset, SEEK_SET) == (off_t)-1) {
558 TIFFError(infilename,
559 "scanline %lu: Seek error",
560 (unsigned long) row);
564 if (read(fd, scanbuf, size) < 0) {
565 TIFFError(infilename,
566 "scanline %lu: Read error",
567 (unsigned long) row);
571 rearrangePixels(scanbuf, width, info_hdr.iBitCount);
573 if (TIFFWriteScanline(out, scanbuf, row, 0)<0) {
574 TIFFError(infilename,
575 "scanline %lu: Write error",
576 (unsigned long) row);
583 /* -------------------------------------------------------------------- */
584 /* Read compressed image data. */
585 /* -------------------------------------------------------------------- */
587 } else if ( info_hdr.iCompression == BMPC_RLE8
588 || info_hdr.iCompression == BMPC_RLE4 ) {
589 uint32 i, j, k, runlength;
590 uint32 compr_size, uncompr_size;
591 unsigned char *comprbuf;
592 unsigned char *uncomprbuf;
594 compr_size = file_hdr.iSize - file_hdr.iOffBits;
595 uncompr_size = width * length;
596 comprbuf = (unsigned char *) _TIFFmalloc( compr_size );
598 TIFFError(infilename,
599 "Can't allocate space for compressed scanline buffer");
602 uncomprbuf = (unsigned char *)_TIFFmalloc(uncompr_size);
604 TIFFError(infilename,
605 "Can't allocate space for uncompressed scanline buffer");
609 lseek(fd, file_hdr.iOffBits, SEEK_SET);
610 read(fd, comprbuf, compr_size);
613 if (info_hdr.iBitCount == 8) { /* RLE8 */
614 while(j < uncompr_size && i < compr_size) {
616 runlength = comprbuf[i++];
619 && i < compr_size ) {
620 uncomprbuf[j++] = comprbuf[i];
626 if (comprbuf[i] == 0) /* Next scanline */
628 else if (comprbuf[i] == 1) /* End of image */
630 else if (comprbuf[i] == 2) { /* Move to... */
632 if (i < compr_size - 1) {
633 j+=comprbuf[i]+comprbuf[i+1]*width;
638 } else { /* Absolute mode */
639 runlength = comprbuf[i++];
640 for (k = 0; k < runlength && j < uncompr_size && i < compr_size; k++)
641 uncomprbuf[j++] = comprbuf[i++];
649 while( j < uncompr_size && i < compr_size ) {
651 runlength = comprbuf[i++];
652 while( runlength > 0 && j < uncompr_size && i < compr_size ) {
653 if ( runlength & 0x01 )
654 uncomprbuf[j++] = (comprbuf[i] & 0xF0) >> 4;
656 uncomprbuf[j++] = comprbuf[i] & 0x0F;
662 if (comprbuf[i] == 0) /* Next scanline */
664 else if (comprbuf[i] == 1) /* End of image */
666 else if (comprbuf[i] == 2) { /* Move to... */
668 if (i < compr_size - 1) {
669 j+=comprbuf[i]+comprbuf[i+1]*width;
674 } else { /* Absolute mode */
675 runlength = comprbuf[i++];
676 for (k = 0; k < runlength && j < uncompr_size && i < compr_size; k++) {
678 uncomprbuf[j++] = comprbuf[i++] & 0x0F;
680 uncomprbuf[j++] = (comprbuf[i] & 0xF0) >> 4;
691 for (row = 0; row < length; row++) {
692 if (TIFFWriteScanline(out,
693 uncomprbuf + (length - row - 1) * width,
695 TIFFError(infilename,
696 "scanline %lu: Write error.\n",
697 (unsigned long) row);
701 _TIFFfree(uncomprbuf);
703 TIFFWriteDirectory(out);
709 _TIFFfree(green_tbl);
723 _TIFFfree(green_tbl);
736 * Image data in BMP file stored in BGR (or ABGR) format. We should rearrange
737 * pixels to RGB (RGBA) format.
740 rearrangePixels(char *buf, uint32 width, uint32 bit_count)
746 case 16: /* FIXME: need a sample file */
749 for (i = 0; i < width; i++, buf += 3) {
759 for (i = 0; i < width; i++, buf += 4) {
761 *buf1++ = *(buf + 2);
762 *buf1++ = *(buf + 1);
773 processCompressOptions(char* opt)
775 if (strcmp(opt, "none") == 0)
776 compression = COMPRESSION_NONE;
777 else if (strcmp(opt, "packbits") == 0)
778 compression = COMPRESSION_PACKBITS;
779 else if (strncmp(opt, "jpeg", 4) == 0) {
780 char* cp = strchr(opt, ':');
782 compression = COMPRESSION_JPEG;
785 if (isdigit((int)cp[1]))
786 quality = atoi(cp+1);
787 else if (cp[1] == 'r' )
788 jpegcolormode = JPEGCOLORMODE_RAW;
792 cp = strchr(cp+1,':');
794 } else if (strncmp(opt, "lzw", 3) == 0) {
795 char* cp = strchr(opt, ':');
797 predictor = atoi(cp+1);
798 compression = COMPRESSION_LZW;
799 } else if (strncmp(opt, "zip", 3) == 0) {
800 char* cp = strchr(opt, ':');
802 predictor = atoi(cp+1);
803 compression = COMPRESSION_DEFLATE;
809 static char* stuff[] = {
810 "bmp2tiff --- convert Windows BMP files to TIFF",
811 "usage: bmp2tiff [options] input.bmp [input2.bmp ...] output.tif",
812 "where options are:",
813 " -r # make each strip have no more than # rows",
815 " -c lzw[:opts] compress output with Lempel-Ziv & Welch encoding",
816 " -c zip[:opts] compress output with deflate encoding",
817 " -c jpeg[:opts]compress output with JPEG encoding",
818 " -c packbits compress output with packbits encoding",
819 " -c none use no compression algorithm on output",
822 " # set compression quality level (0-100, default 75)",
823 " r output color image as RGB rather than YCbCr",
824 "For example, -c jpeg:r:50 to get JPEG-encoded RGB data with 50% comp. quality",
826 "LZW and deflate options:",
827 " # set predictor value",
828 "For example, -c lzw:2 to get LZW-encoded data with horizontal differencing",
829 " -o out.tif write output to out.tif",
830 " -h this help message",
841 fprintf(stderr, "%s\n\n", TIFFGetVersion());
842 for (i = 0; stuff[i] != NULL; i++)
843 fprintf(stderr, "%s\n", stuff[i]);
847 /* vim: set ts=8 sts=8 sw=8 noet: */