I wrote a raytracer for a computer graphics class in college and needed to write to BMP format. Here's my code:
bmpwriter.h:
bool write_bitmap(const char *filename, const char *buffer, int width, int height);
bmpwriter.cpp:
#include
#include "bmpwriter.h"
// stuff from wingdi.h
typedef unsigned short WORD;
typedef unsigned int DWORD;
#define FAR
#pragma pack(push, 2)
typedef struct tagBITMAPFILEHEADER {
WORD bfType;
DWORD bfSize;
WORD bfReserved1;
WORD bfReserved2;
DWORD bfOffBits;
} BITMAPFILEHEADER, FAR *LPBITMAPFILEHEADER, *PBITMAPFILEHEADER;
typedef struct tagBITMAPCOREHEADER {
DWORD bcSize; /* used to get to color table */
WORD bcWidth;
WORD bcHeight;
WORD bcPlanes;
WORD bcBitCount;
} BITMAPCOREHEADER, FAR *LPBITMAPCOREHEADER, *PBITMAPCOREHEADER;
#pragma pack(pop)
bool write_bitmap(const char *filename, const char *buffer, int width, int height) {
BITMAPFILEHEADER bfh = { 0x4D42, sizeof(BITMAPFILEHEADER) + sizeof(BITMAPCOREHEADER) + width * height * 3, 0, 0, sizeof(BITMAPFILEHEADER) + sizeof(BITMAPCOREHEADER) };
BITMAPCOREHEADER bch = { sizeof(BITMAPCOREHEADER), width, height, 1, 24 };
FILE *pf = fopen(filename, "wb");
if (pf == NULL) {
return false;
}
else {
fwrite(&bfh, sizeof(BITMAPFILEHEADER), 1, pf);
fwrite(&bch, sizeof(BITMAPCOREHEADER), 1, pf);
fwrite(buffer, 3 * width, height, pf);
fclose(pf);
return true;
}
}
The buffer is an array of (3 × width × height) 8-bit samples, which are the RGB colors at each pixel in the image. I don't remember whether BMP uses RGB or BGR ordering, so just play with it until you get it right.