summaryrefslogtreecommitdiff
path: root/src/Fl_BMP_Image.cxx
blob: b2faf2de938c053ec9389b70f4828e3bcc6713d6 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
//
// "$Id$"
//
// Fl_BMP_Image routines.
//
// Copyright 1997-2010 by Easy Software Products.
// Image support by Matthias Melcher, Copyright 2000-2009.
//
// This library is free software. Distribution and use rights are outlined in
// the file "COPYING" which should have been included with this file.  If this
// file is missing or damaged, see the license at:
//
//     http://www.fltk.org/COPYING.php
//
// Please report all bugs and problems on the following page:
//
//     http://www.fltk.org/str.php
//
// Contents:
//
//   Fl_BMP_Image::Fl_BMP_Image() - Load a BMP image file.
//

//
// Include necessary header files...
//

#include <FL/Fl_BMP_Image.H>
#include <FL/fl_utf8.h>
#include <FL/Fl.H>
#include <stdio.h>
#include <stdlib.h>


//
// BMP definitions...
//

#ifndef BI_RGB
#  define BI_RGB       0             // No compression - straight BGR data
#  define BI_RLE8      1             // 8-bit run-length compression
#  define BI_RLE4      2             // 4-bit run-length compression
#  define BI_BITFIELDS 3             // RGB bitmap with RGB masks
#endif // !BI_RGB


//
// Local reader class...
//

/*
 This class reads data chunks from a file or from memory in LSB-first
 byte order.
 
 TODO: GIFReader and BMPReader are very similar and should be combined to avoid
 code duplication.
 */
class BMPReader
{
public:
  // Create the reader.
  BMPReader() :
  pIsFile(0), pIsData(0),
  pFile(0L), pData(0L), pStart(0L),
  pName(0L)
  { }
  // Initialize the reader to access the file system, filename is copied
  // and stored.
  int open(const char *filename) {
    if (!filename)
      return -1;
    pName = strdup(filename);
    if ( (pFile = fl_fopen(filename, "rb")) == NULL ) {
      return -1;
    }
    pIsFile = 1;
    return 0;
  }
  // Initialize the reader for memory access, name is copied and stored
  int open(const char *imagename, const unsigned char *data) {
    if (imagename)
      pName = strdup(imagename);
    if (data) {
      pStart = pData = data;
      pIsData = 1;
      return 0;
    } else {
      return -1;
    }
  }
  // Close and destroy the reader
  ~BMPReader() {
    if (pIsFile && pFile) {
      fclose(pFile);
    }
    if (pName)
      ::free(pName);
  }
  // Read a single byte form memory or a file
  uchar read_byte() {
    if (pIsFile) {
      return getc(pFile);
    } else if (pIsData) {
      return *pData++;
    } else {
      return 0;
    }
  }
  // Read a 16-bit unsigned integer, LSB-first
  unsigned short read_word() {
    unsigned char b0, b1;  // Bytes from file
    if (pIsFile) {
      b0 = (uchar)getc(pFile);
      b1 = (uchar)getc(pFile);
      return ((b1 << 8) | b0);
    } else if (pIsData) {
      b0 = *pData++;
      b1 = *pData++;
      return ((b1 << 8) | b0);
    } else {
      return 0;
    }
  }
  // Read a 32-bit unsigned integer, LSB-first
  unsigned int read_dword() {
    unsigned char b0, b1, b2, b3;  // Bytes from file
    if (pIsFile) {
      b0 = (uchar)getc(pFile);
      b1 = (uchar)getc(pFile);
      b2 = (uchar)getc(pFile);
      b3 = (uchar)getc(pFile);
      return ((((((b3 << 8) | b2) << 8) | b1) << 8) | b0);
    } else if (pIsData) {
      b0 = *pData++;
      b1 = *pData++;
      b2 = *pData++;
      b3 = *pData++;
      return ((((((b3 << 8) | b2) << 8) | b1) << 8) | b0);
    } else {
      return 0;
    }
  }
  // Read a 32-bit signed integer, LSB-first
  int read_long() {
    return (int)read_dword();
  };
  // Move the current read position to a byte offset fro the beginning of the
  // file or the original start address in memory
  void seek(unsigned int n) {
    if (pIsFile) {
      fseek(pFile, n , SEEK_SET);
    } else if (pIsData) {
      pData = pStart + n;
    }
  }
  // return the name or filename for this reader
  const char *name() { return pName; }
private:
  // open() sets this if we read form a file
  char pIsFile;
  // open() sets this if we read form memory
  char pIsData;
  // a pointer to the opened file
  FILE *pFile;
  // a pointer to the current byte in memory
  const unsigned char *pData;
  // a pointer to the start of the image data
  const unsigned char *pStart;
  // a copy of the name associated with this reader
  char *pName;
};


/**
 \brief The constructor loads the named BMP image from the given bmp filename.

 The destructor frees all memory and server resources that are used by
 the image.

 Use Fl_Image::fail() to check if Fl_BMP_Image failed to load. fail() returns
 ERR_FILE_ACCESS if the file could not be opened or read, ERR_FORMAT if the
 BMP format could not be decoded, and ERR_NO_IMAGE if the image could not
 be loaded for another reason.

 \param[in] filename a full path and name pointing to a valid BMP file.

 \see Fl_BMP_Image::Fl_BMP_Image(const char *imagename, const unsigned char *data)
 */
Fl_BMP_Image::Fl_BMP_Image(const char *filename) // I - File to read
: Fl_RGB_Image(0,0,0)
{
  BMPReader f;
  if (f.open(filename)==-1) {
    ld(ERR_FILE_ACCESS);
  } else {
    load_bmp_(f);
  }
}

/**
 \brief Read a BMP image from memory.

 Construct an image from a block of memory inside the application. Fluid offers
 "binary Data" chunks as a great way to add image data into the C++ source code.
 imagename can be NULL. If a name is given, the image is added to the list of
 shared images and will be available by that name.

 Use Fl_Image::fail() to check if Fl_BMP_Image failed to load. fail() returns
 ERR_FILE_ACCESS if the file could not be opened or read, ERR_FORMAT if the
 BMP format could not be decoded, and ERR_NO_IMAGE if the image could not
 be loaded for another reason.

 \param[in] imagename  A name given to this image or NULL
 \param[in] data       Pointer to the start of the BMP image in memory. This code will not check for buffer overruns.

 \see Fl_BMP_Image::Fl_BMP_Image(const char *filename)
 \see Fl_Shared_Image
*/
Fl_BMP_Image::Fl_BMP_Image(const char *imagename, const unsigned char *data)
: Fl_RGB_Image(0,0,0)
{
  BMPReader d;
  if (d.open(imagename, data)==-1) {
    ld(ERR_FILE_ACCESS);
  } else {
    load_bmp_(d);
  }
}

/*
 This method reads BMP image data and creates an RGB or RGBA image. The BMP
 format supports only 1 bit for alpha. To avoid code duplication, we use
 a BMPReader that reads data from either a file or from memory.
 */
void Fl_BMP_Image::load_bmp_(class BMPReader &rdr)
{
  int     info_size,    // Size of info header
          depth,        // Depth of image (bits)
          bDepth = 3,   // Depth of image (bytes)
          compression,  // Type of compression
          colors_used,  // Number of colors used
          x, y,         // Looping vars
          color,        // Color of RLE pixel
          repcount,     // Number of times to repeat
          temp,         // Temporary color
          align,        // Alignment bytes
          dataSize,     // number of bytes in image data set
          row_order,    // 1 = normal;  -1 = flipped row order
          start_y,      // Beginning Y
          end_y;        // Ending Y
  long    offbits;      // Offset to image data
  uchar   bit,          // Bit in image
          byte;         // Byte in image
  uchar   *ptr;         // Pointer into pixels
  uchar   colormap[256][3]; // Colormap
  uchar   havemask;     // Single bit mask follows image data
  int     use_5_6_5;    // Use 5:6:5 for R:G:B channels in 16 bit images

  // Reader is already open at this point.

  // Get the header...
  byte = rdr.read_byte();	// Check "BM" sync chars
  bit  = rdr.read_byte();
  if (byte != 'B' || bit != 'M') {
    ld(ERR_FORMAT);
    return;
  }

  rdr.read_dword();		// Skip size
  rdr.read_word();		// Skip reserved stuff
  rdr.read_word();
  offbits = (long)rdr.read_dword();// Read offset to image data

  // Then the bitmap information...
  info_size = rdr.read_dword();

  //  printf("offbits = %ld, info_size = %d\n", offbits, info_size);

  havemask  = 0;
  row_order = -1;
  use_5_6_5 = 0;

  if (info_size < 40) {
    // Old Windows/OS2 BMP header...
    w(rdr.read_word());
    h(rdr.read_word());
    rdr.read_word();
    depth = rdr.read_word();
    compression = BI_RGB;
    colors_used = 0;

    repcount = info_size - 12;
  } else {
    // New BMP header...
    w(rdr.read_long());
    // If the height is negative, the row order is flipped
    temp = rdr.read_long();
    if (temp < 0) row_order = 1;
    h(abs(temp));
    rdr.read_word();
    depth = rdr.read_word();
    compression = rdr.read_dword();
    dataSize = rdr.read_dword();
    rdr.read_long();
    rdr.read_long();
    colors_used = rdr.read_dword();
    rdr.read_dword();

    repcount = info_size - 40;

    if (!compression && depth>=8 && w()>32/depth) {
      int Bpp = depth/8;
      int maskSize = (((w()*Bpp+3)&~3)*h()) + (((((w()+7)/8)+3)&~3)*h());
      if (maskSize==2*dataSize) {
        havemask = 1;
        h(h()/2);
        bDepth = 4;
      }
    }
  }

  //  printf("w() = %d, h() = %d, depth = %d, compression = %d, colors_used = %d, repcount = %d\n",
  //         w(), h(), depth, compression, colors_used, repcount);

  // Skip remaining header bytes...
  while (repcount > 0) {
    rdr.read_byte();
    repcount --;
  }

  // Check header data...
  if (!w() || !h() || !depth) {
    w(0); h(0); d(0); ld(ERR_FORMAT);
    return;
  }

  // Get colormap...
  if (colors_used == 0 && depth <= 8)
    colors_used = 1 << depth;

  for (repcount = 0; repcount < colors_used; repcount ++) {
    // Read BGR color...
    colormap[repcount][0] = rdr.read_byte();
    colormap[repcount][1] = rdr.read_byte();
    colormap[repcount][2] = rdr.read_byte();

    // Skip pad byte for new BMP files...
    if (info_size > 12) rdr.read_byte();
  }

  // Read first dword of colormap. It tells us if 5:5:5 or 5:6:5 for 16 bit
  if (depth == 16)
    use_5_6_5 = (rdr.read_dword() == 0xf800);

  // Set byte depth for RGBA images
  if (depth == 32)
    bDepth=4;

  // Setup image and buffers...
  d(bDepth);
  if (offbits) rdr.seek(offbits);

  if (((size_t)w()) * h() * d() > max_size() ) {
    Fl::warning("BMP file \"%s\" is too large!\n", rdr.name());
    w(0); h(0); d(0); ld(ERR_FORMAT);
    return;
  }
  array = new uchar[w() * h() * d()];
  alloc_array = 1;

  // Read the image data...
  color = 0;
  repcount = 0;
  align = 0;
  byte  = 0;
  temp  = 0;

  if (row_order < 0) {
    start_y = h() - 1;
    end_y   = -1;
  } else {
    start_y = 0;
    end_y   = h();
  }

  for (y = start_y; y != end_y; y += row_order) {
    ptr = (uchar *)array + y * w() * d();

    switch (depth)
    {
      case 1 : // Bitmap
        for (x = w(), bit = 128; x > 0; x --) {
          if (bit == 128) byte = rdr.read_byte();

          if (byte & bit) {
            *ptr++ = colormap[1][2];
            *ptr++ = colormap[1][1];
            *ptr++ = colormap[1][0];
          } else {
            *ptr++ = colormap[0][2];
            *ptr++ = colormap[0][1];
            *ptr++ = colormap[0][0];
          }

          if (bit > 1)
            bit >>= 1;
          else
            bit = 128;
        }

        // Read remaining bytes to align to 32 bits...
        for (temp = (w() + 7) / 8; temp & 3; temp ++) {
          rdr.read_byte();
        }
        break;

      case 4 : // 16-color
        for (x = w(), bit = 0xf0; x > 0; x --) {
          // Get a new repcount as needed...
          if (repcount == 0) {
            if (compression != BI_RLE4) {
              repcount = 2;
              color = -1;
            } else {
              while (align > 0) {
                align --;
                rdr.read_byte();
              }

              if ((repcount = rdr.read_byte()) == 0) {
                if ((repcount = rdr.read_byte()) == 0) {
                  // End of line...
                  x ++;
                  continue;
                } else if (repcount == 1) {
                  // End of image...
                  break;
                } else if (repcount == 2) {
                  // Delta...
                  repcount = rdr.read_byte() * rdr.read_byte() * w();
                  color = 0;
                } else {
                  // Absolute...
                  color = -1;
                  align = ((4 - (repcount & 3)) / 2) & 1;
                }
              } else {
                color = rdr.read_byte();
              }
            }
          }

          // Get a new color as needed...
          repcount --;

          // Extract the next pixel...
          if (bit == 0xf0) {
            // Get the next color byte as needed...
            if (color < 0) temp = rdr.read_byte();
            else temp = color;

            // Copy the color value...
            *ptr++ = colormap[(temp >> 4) & 15][2];
            *ptr++ = colormap[(temp >> 4) & 15][1];
            *ptr++ = colormap[(temp >> 4) & 15][0];

            bit  = 0x0f;
          } else {
            bit  = 0xf0;

            // Copy the color value...
            *ptr++ = colormap[temp & 15][2];
            *ptr++ = colormap[temp & 15][1];
            *ptr++ = colormap[temp & 15][0];
          }

        }

        if (!compression) {
          // Read remaining bytes to align to 32 bits...
          for (temp = (w() + 1) / 2; temp & 3; temp ++) {
            rdr.read_byte();
          }
        }
        break;

      case 8 : // 256-color
        for (x = w(); x > 0; x --) {
          // Get a new repcount as needed...
          if (compression != BI_RLE8) {
            repcount = 1;
            color = -1;
          }

          if (repcount == 0) {
            while (align > 0) {
              align --;
              rdr.read_byte();
            }

            if ((repcount = rdr.read_byte()) == 0) {
              if ((repcount = rdr.read_byte()) == 0) {
                // End of line...
                x ++;
                continue;
              } else if (repcount == 1) {
                // End of image...
                break;
              } else if (repcount == 2) {
                // Delta...
                repcount = rdr.read_byte() * rdr.read_byte() * w();
                color = 0;
              } else {
                // Absolute...
                color = -1;
                align = (2 - (repcount & 1)) & 1;
              }
            } else {
              color = rdr.read_byte();
            }
          }

          // Get a new color as needed...
          if (color < 0) temp = rdr.read_byte();
          else temp = color;

          repcount --;

          // Copy the color value...
          *ptr++ = colormap[temp][2];
          *ptr++ = colormap[temp][1];
          *ptr++ = colormap[temp][0];
          if (havemask) ptr++;
        }

        if (!compression) {
          // Read remaining bytes to align to 32 bits...
          for (temp = w(); temp & 3; temp ++) {
            rdr.read_byte();
          }
        }
        break;

      case 16 : // 16-bit 5:5:5 or 5:6:5 RGB
        for (x = w(); x > 0; x --, ptr += bDepth) {
          uchar b = rdr.read_byte(), a = rdr.read_byte() ;
          if (use_5_6_5) {
            ptr[2] = (uchar)(( b << 3 ) & 0xf8);
            ptr[1] = (uchar)(((a << 5) & 0xe0) | ((b >> 3) & 0x1c));
            ptr[0] = (uchar)(a & 0xf8);
          } else {
            ptr[2] = (uchar)((b << 3) & 0xf8);
            ptr[1] = (uchar)(((a << 6) & 0xc0) | ((b >> 2) & 0x38));
            ptr[0] = (uchar)((a<<1) & 0xf8);
          }
        }

        // Read remaining bytes to align to 32 bits...
        for (temp = w() * 2; temp & 3; temp ++) {
          rdr.read_byte();
        }
        break;

      case 24 : // 24-bit RGB
        for (x = w(); x > 0; x --, ptr += bDepth) {
          ptr[2] = rdr.read_byte();
          ptr[1] = rdr.read_byte();
          ptr[0] = rdr.read_byte();
        }

        // Read remaining bytes to align to 32 bits...
        for (temp = w() * 3; temp & 3; temp ++) {
          rdr.read_byte();
        }
        break;

      case 32 : // 32-bit RGBA
        for (x = w(); x > 0; x --, ptr += bDepth) {
          ptr[2] = rdr.read_byte();
          ptr[1] = rdr.read_byte();
          ptr[0] = rdr.read_byte();
          ptr[3] = rdr.read_byte();
        }
        break;
    }
  }
  
  if (havemask) {
    for (y = h() - 1; y >= 0; y --) {
      ptr = (uchar *)array + y * w() * d() + 3;
      for (x = w(), bit = 128; x > 0; x --, ptr+=bDepth) {
        if (bit == 128) byte = rdr.read_byte();
        if (byte & bit)
          *ptr = 0;
        else
          *ptr = 255;
        if (bit > 1)
          bit >>= 1;
        else
          bit = 128;
      }
      // Read remaining bytes to align to 32 bits...
      for (temp = (w() + 7) / 8; temp & 3; temp ++)
        rdr.read_byte();
    }
  }
  // File is closed when returning...
}


//
// End of "$Id$".
//