- FILE *f;
- bmphd_t bhd;
- binfo_t info;
- // int pxlsize = 1;
- int rowbytes, i, pixbytes;
- char *scanline;
-
- // open file
- if ((f = fopen(filename, "rb")) == NULL)
- {
- Error("Unable to open file");// %s.", filename);
- }
-
- // read in bitmap header
- if (fread(&bhd, sizeof(bhd), 1, f) != 1)
- {
- fclose(f);
- Error("Unable to read in bitmap header.");
- }
-
- // make sure we have a valid bitmap file
- if (bhd.bfType != BMP_SIGNATURE_WORD)
- {
- fclose(f);
- Error("Invalid BMP file");//: %s", filename);
- }
-
- // load in info header
- if (fread(&info, sizeof(info), 1, f) != 1)
- {
- fclose(f);
- Error("Unable to read bitmap info header.");
- }
-
- // make sure this is an info type of bitmap
- if (info.biSize != sizeof(binfo_t))
- {
- fclose(f);
- Error("We only support the info bitmap type.");
- }
-
- // PrintHeader(&info);
-
- bit->bpp = info.biBitCount;
- bit->width = info.biWidth;
- bit->height = info.biHeight;
- bit->data = NULL;
- bit->palette = NULL;
-
- //currently we only read in 8 and 24 bit bmp files
- if (info.biBitCount == 8) pixbytes = 1;
- else if (info.biBitCount == 24) pixbytes = 3;
- else
- {
- Error("Only 8BPP and 24BPP supported");
- //Error("BPP %d not supported.", info.biBitCount);
- }
-
- // if this is an eight bit image load palette
- if (pixbytes == 1)
- {
- drgb_t q;
-
- bit->palette = reinterpret_cast<rgb_t*>(g_malloc(sizeof(rgb_t) * 256));
-
- for (i = 0; i < 256; i++)
- {
- if (fread(&q, sizeof(drgb_t), 1, f) != 1)
- {
- fclose(f); g_free(bit->palette);
- Error("Unable to read palette.");
- }
-
- bit->palette[i].r = q.red;
- bit->palette[i].g = q.green;
- bit->palette[i].b = q.blue;
- }
- }
-
- // position to start of bitmap
- fseek(f, bhd.bfOffBits, SEEK_SET);
-
- // create scanline to read data into
- rowbytes = ((info.biWidth * pixbytes) + 3) / 4;
- rowbytes *= 4;
-
- scanline = reinterpret_cast<char*>(g_malloc(rowbytes));
-
- // alloc space for new bitmap
- bit->data = reinterpret_cast<unsigned char*>(g_malloc(info.biWidth * pixbytes * info.biHeight));
-
- // read in image
- for (i = 0; i < info.biHeight; i++)
- {
- BMPLine(f, scanline, pixbytes, info.biWidth, info.biCompression);
-
- // store line
- memcpy(&bit->data[info.biWidth * pixbytes * (info.biHeight - i - 1)], scanline, info.biWidth * pixbytes);
- }
-
- g_free(scanline);
- fclose(f);