Skip to content

Instantly share code, notes, and snippets.

@muiz6
Created June 27, 2020 12:05
Show Gist options
  • Select an option

  • Save muiz6/51139825c7d38aa58b03034ed997a1aa to your computer and use it in GitHub Desktop.

Select an option

Save muiz6/51139825c7d38aa58b03034ed997a1aa to your computer and use it in GitHub Desktop.
Example code on how to write a bitmap file from scratch.
#include <cstdint> // for specific size integers
#include <fstream> // for file handling
using namespace std;
struct BmpHeader {
char bitmapSignatureBytes[2] = {'B', 'M'};
uint32_t sizeOfBitmapFile = 54 + 786432; // total size of bitmap file
uint32_t reservedBytes = 0;
uint32_t pixelDataOffset = 54;
} bmpHeader;
struct BmpInfoHeader {
uint32_t sizeOfThisHeader = 40;
int32_t width = 512; // in pixels
int32_t height = 512; // in pixels
uint16_t numberOfColorPlanes = 1; // must be 1
uint16_t colorDepth = 24;
uint32_t compressionMethod = 0;
uint32_t rawBitmapDataSize = 0; // generally ignored
int32_t horizontalResolution = 3780; // in pixel per meter
int32_t verticalResolution = 3780; // in pixel per meter
uint32_t colorTableEntries = 0;
uint32_t importantColors = 0;
} bmpInfoHeader;
struct Pixel {
uint8_t blue = 255;
uint8_t green = 255;
uint8_t red = 0;
} pixel;
int main(int argc, char **argv) {
ofstream fout("output.bmp", ios::binary);
fout.write((char *) &bmpHeader, 14);
fout.write((char *) &bmpInfoHeader, 40);
// writing pixel data
size_t numberOfPixels = bmpInfoHeader.width * bmpInfoHeader.height;
for (int i = 0; i < numberOfPixels; i++) {
fout.write((char *) &pixel, 3);
}
fout.close();
return 0;
}
@BlackDogWhite
Copy link

BlackDogWhite commented Jun 18, 2025

when I compile and run this code, the resultant file seems not to be the proper format of a BMP file. That is, Paint, Windows Photo app, say the file format is invalid.
added a #pragma pack (1) to the top of the code and now it works properly.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment