Created
September 23, 2020 00:57
-
-
Save mmozeiko/454261be848a0be0a22bafb8abd14a4f to your computer and use it in GitHub Desktop.
saving simple 32-bit RGBA top-down bmp file
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <stdarg.h> | |
#include <stdio.h> | |
static void write(FILE* f, const char* fmt, ...) | |
{ | |
va_list ap; | |
va_start(ap, fmt); | |
char ch; | |
while ((ch = *fmt++)) | |
{ | |
if (ch == '0') | |
{ | |
fputc((char)0, f); | |
} | |
else if (ch == 'o') | |
{ | |
fputc((char)0, f); | |
fputc((char)0, f); | |
} | |
else if (ch == 'O') | |
{ | |
fputc((char)0, f); | |
fputc((char)0, f); | |
fputc((char)0, f); | |
fputc((char)0, f); | |
} | |
else if (ch == '1') | |
{ | |
int x = va_arg(ap, int); | |
fputc((char)x, f); | |
} | |
else if (ch == '2') | |
{ | |
int x = va_arg(ap, int); | |
fputc((char)x, f); | |
fputc((char)(x >> 8), f); | |
} | |
else if (ch == '4') | |
{ | |
int x = va_arg(ap, int); | |
fputc((char)x, f); | |
fputc((char)(x >> 8), f); | |
fputc((char)(x >> 16), f); | |
fputc((char)(x >> 24), f); | |
} | |
} | |
va_end(ap); | |
} | |
#define RGBA(r,g,b,a) ( ((a) << 24) | ((b) << 16) | ((g) << 8) | ((r) << 0) ) | |
static void write_bmp32(const char* fname, int width, int height, const void* data) | |
{ | |
FILE* f = fopen(fname, "wb"); | |
if (f) | |
{ | |
int fheader = 14; // = sizeof(BITMAPFILEHEADER) | |
int iheader = 108; // = sizeof(BITMAPV4HEADER) | |
int dsize = width * height * 4; | |
int fsize = fheader + iheader + dsize; | |
int doffset = fheader + iheader; | |
int planes = 1; | |
int bitcount = 32; | |
int compression = 3; // = BI_BITFIELDS | |
int red = RGBA(255,0,0,0); | |
int green = RGBA(0,255,0,0); | |
int blue = RGBA(0,0,255,0); | |
int alpha = RGBA(0,0,0,255); | |
int colorspace = 0x57696E20; // = LCS_WINDOWS_COLOR_SPACE | |
write(f, "11 4oo4 4442244OOOO 4444 4 OOOOOOOOOOOO", | |
'B', 'M', | |
fsize, doffset, | |
iheader, width, -height, planes, bitcount, compression, dsize, | |
red, green, blue, alpha, | |
colorspace); | |
fwrite(data, width * height * 4, 1, f); | |
fclose(f); | |
} | |
} | |
int main() | |
{ | |
unsigned data[4*2] = { | |
RGBA(255,0,0,255), RGBA(0,255,0,255), RGBA(0,0,255,255), RGBA(255,255,255,255), | |
RGBA(255,0,0,128), RGBA(0,255,0,128), RGBA(0,0,255,128), RGBA(255,255,255,128), | |
}; | |
write_bmp32("test.bmp", 4, 2, data); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment