Writing Bitmap Files in Windows

This is a bitmap file writing example. I compiled it with MinGW (gcc). It generates the following image and saves it as a bitmap file called “image.bmp”.

Bitmap image saved by my example program.

Here’s the source code:

//
// WriteBMP.c - Bitmap file writing example program
// Written by Ted Burke - last modified 30-11-2011
//
// To compile with MinGW:
//
//	gcc -o WriteBMP.exe WriteBMP.c
//

#include <windows.h>
#include <stdio.h>

int main()
{
	// Image properties
	int x, y, w = 320, h = 240;
	unsigned char p[h][w][3];

	// Bitmap structures to be written to file
	BITMAPFILEHEADER bfh;
	BITMAPINFOHEADER bih;

	// Fill BITMAPFILEHEADER structure
	memcpy((char *)&bfh.bfType, "BM", 2);
	bfh.bfSize = sizeof(bfh) + sizeof(bih) + 3*h*w;
	bfh.bfReserved1 = 0;
	bfh.bfReserved2 = 0;
	bfh.bfOffBits = sizeof(bfh) + sizeof(bih);

	// Fill BITMAPINFOHEADER structure
	bih.biSize = sizeof(bih);
	bih.biWidth = w;
	bih.biHeight = h;
	bih.biPlanes = 1;
	bih.biBitCount = 24;
	bih.biCompression = BI_RGB; // uncompressed 24-bit RGB
	bih.biSizeImage = 0; // can be zero for BI_RGB bitmaps
	bih.biXPelsPerMeter = 3780; // 96dpi equivalent
	bih.biYPelsPerMeter = 3780;
	bih.biClrUsed = 0;
	bih.biClrImportant = 0;

	// Generate pixel data
	for (y=0 ; y<h ; ++y)
	{
		for (x=0 ; x<w ; ++x)
		{
			p[y][x][0] = 255 * (y/(double)h);
			p[y][x][1] = 255 * (x/(double)w);
			p[y][x][2] = 0;
		}
	}

	// Open bitmap file (binary mode)
	FILE *f;
	f = fopen("image.bmp", "wb");

	// Write bitmap file header
	fwrite(&bfh, 1, sizeof(bfh), f);
	fwrite(&bih, 1, sizeof(bih), f);

	// Write bitmap pixel data starting with the
	// bottom line of pixels, left hand side
	for (y=h-1 ; y>=0 ; --y)
	{
		for (x=0 ; x<w ; ++x)
		{
			// Write pixel components in BGR order
			fputc(p[y][x][2], f);
			fputc(p[y][x][1], f);
			fputc(p[y][x][0], f);
		}
	}

	// Close bitmap file
	fclose(f);

	// Exit normally
	return 0;
}
This entry was posted in Uncategorized and tagged , , , , , , . Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s