Skip to content

Instantly share code, notes, and snippets.

@rogersguedes
Forked from binshengliu/write_bmp.c
Last active August 21, 2018 20:53
Show Gist options
  • Save rogersguedes/952badc3aa0fe415103d1ce727ff7be8 to your computer and use it in GitHub Desktop.
Save rogersguedes/952badc3aa0fe415103d1ce727ff7be8 to your computer and use it in GitHub Desktop.
Writing bmp in C. see http://pastebin.com/qCRHiPEZ
#include <stdlib.h>
#include <fcntl.h>
#include <unistd.h>
#include <stdio.h>
//define pixelformat of windows bitmap, notice the unusual ordering of colors
typedef struct {
unsigned char B;
unsigned char G;
unsigned char R;
} pixel;
//supply an array of pixels[height][width] <- notice that height comes first
int writeBMP(char* filename, unsigned int width, unsigned int height, pixel** pixels) {
int fd = open(filename, O_WRONLY|O_CREAT|O_TRUNC,S_IRUSR|S_IWUSR|S_IRGRP|S_IWGRP|S_IROTH|S_IWOTH);
static unsigned char header[54] = {
0x42, 0x4d, //BM
0x00, 0x00, 0x00, 0x00, //File Size, fill later
0x00, 0x00, 0x00, 0x00, //reserved, filled with zeros
0x36, 0x00, 0x00, 0x00, //pixel offset 0x36 = 54
0x28, 0x00, 0x00, 0x00, //BITMAPINFOHEADER
0x00, 0x00, 0x00, 0x00, //width
0x00, 0x00, 0x00, 0x00, //height
0x01, 0x00, //number of color planes
0x18, 0x00, //bits per pixel 0x18 = 24
0x00, 0x00, 0x00, 0x00, //no compression
0x00, 0x00, 0x00, 0x00, //size of raw data in pixel array, fill later
0x13, 0x0b, 0x00, 0x00, //Horizontal Resolution
0x13, 0x0b, 0x00, 0x00, //Vertical Resolution
0x00, 0x00, 0x00, 0x00, //Number of colors
0x00, 0x00, 0x00, 0x00 //important colors
}; //rest is zeroes
unsigned int pixelBytesPerRow = width*sizeof(pixel);
unsigned int paddingBytesPerRow = (4-(pixelBytesPerRow%4))%4;
unsigned int* sizeOfFileEntry = (unsigned int*) &header[2];
*sizeOfFileEntry = 54 + (pixelBytesPerRow+paddingBytesPerRow)*height;
unsigned int* widthEntry = (unsigned int*) &header[18];
*widthEntry = width;
unsigned int* heightEntry = (unsigned int*) &header[22];
*heightEntry = height;
write(fd, header, 54);
static unsigned char zeroes[3] = {0,0,0}; //for padding
for (int row = 0; row < height; row++) {
write(fd,pixels[row],pixelBytesPerRow);
write(fd,zeroes,paddingBytesPerRow);
}
close(fd);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment