Skip to content

Commit

Permalink
Ability to store into BMP format
Browse files Browse the repository at this point in the history
  • Loading branch information
tisnik committed May 23, 2024
1 parent 7478377 commit 6060520
Showing 1 changed file with 55 additions and 0 deletions.
55 changes: 55 additions & 0 deletions svitava/svitava.c
Original file line number Diff line number Diff line change
Expand Up @@ -755,11 +755,66 @@ int ppm_write_ascii(unsigned int width, unsigned int height,
return 0;
}

int bmp_write(unsigned int width, unsigned int height,
unsigned char *pixels, const char *file_name) {
unsigned char bmp_header[] = { /* BMP header structure: */
0x42, 0x4d, /* magic number */
0x46, 0x00, 0x00, 0x00, /* size of header=70 bytes */
0x00, 0x00, /* unused */
0x00, 0x00, /* unused */
0x36, 0x00, 0x00, 0x00, /* 54 bytes - offset to data */
0x28, 0x00, 0x00, 0x00, /* 40 bytes - bytes in DIB header */
0x00, 0x00, 0x00, 0x00, /* width of bitmap */
0x00, 0x00, 0x00, 0x00, /* height of bitmap */
0x01, 0x0, /* 1 pixel plane */
0x18, 0x00, /* 24 bpp */
0x00, 0x00, 0x00, 0x00, /* no compression */
0x00, 0x00, 0x00, 0x00, /* size of pixel array */
0x13, 0x0b, 0x00, 0x00, /* 2835 pixels/meter */
0x13, 0x0b, 0x00, 0x00, /* 2835 pixels/meter */
0x00, 0x00, 0x00, 0x00, /* color palette */
0x00, 0x00, 0x00, 0x00, /* important colors */
};
FILE *fout;
int x, y;

bmp_header[18] = width & 0xff;
bmp_header[19] = (width >> 8) & 0xff;
bmp_header[20] = (width >> 16) & 0xff;
bmp_header[21] = (width >> 24) & 0xff;
bmp_header[22] = height & 0xff;
bmp_header[23] = (height >> 8) & 0xff;
bmp_header[24] = (height >> 16) & 0xff;
bmp_header[25] = (height >> 24) & 0xff;

fout = fopen(file_name, "wb");
if (!fout) {
return 1;
}
fwrite(bmp_header, sizeof(bmp_header), 1, fout);

/* pixel array */
for (y = height - 1; y >= 0; y--) {
unsigned char *p = pixels + y * width * 4;
for (x = 0; x < width; x++) {
/* swap RGB */
fwrite(p+2, 1, 1, fout);
fwrite(p+1, 1, 1, fout);
fwrite(p, 1, 1, fout);
/* next pixel */
p+=4;
}
}
fclose(fout);
return 0;
}

int main(void) {
#define WIDTH 256
#define HEIGHT 256
unsigned char *pixels = (unsigned char *)malloc(WIDTH * HEIGHT * 4);
render_test_rgb_image(WIDTH, HEIGHT, pixels, 0);
ppm_write_ascii(WIDTH, HEIGHT, pixels, "test_rgb_1.ppm");
bmp_write(WIDTH, HEIGHT, pixels, "test_rgb_1.bmp");
return 0;
}

0 comments on commit 6060520

Please sign in to comment.