hbmap: fix iterator truncation when size_t < 32bit
[rofl0r-agsutils.git] / BitmapFuncs.h
blob0cb21e75676704584ff778dd74edcef43b0cd0b2
1 #ifndef BITMAPFUNCS_H
2 #define BITMAPFUNCS_H
4 #include "Bitmap.h"
5 #include "ImageData.h"
6 #include "endianness.h"
7 #include <stdlib.h>
8 #include <stdio.h>
10 static int pad_bmp(ImageData *d) {
11 unsigned stride = ((((d->width * d->bytesperpixel*8) + 31) & ~31) >> 3);
12 if(stride == d->width * d->bytesperpixel) return -1;
13 unsigned x,y;
14 unsigned outsz = d->height * stride;
15 unsigned char *out = malloc(outsz), *p = d->data, *q = out;
16 if(!out) return 0;
17 for(y = 0; y < d->height; ++y) {
18 for(x = 0; x < d->width*d->bytesperpixel; ++x)
19 *(q++) = *(p++);
20 for(; x < stride; ++x)
21 *(q++) = 0;
23 free(d->data);
24 d->data = out;
25 d->data_size = outsz;
26 return 1;
28 static void write_bmp(char *name, ImageData *d) {
29 FILE *f = fopen(name, "wb");
30 if(f) {
31 struct BITMAPINFOHEADER_X hdr = {
32 .bfType = end_htole16(0x4D42),
33 .bfSize = end_htole32(sizeof(hdr) + d->data_size),
34 .bfOffsetBits = end_htole32(sizeof(hdr)),
35 .biSize = end_htole32(sizeof(hdr)-14),
36 .biWidth = end_htole32(d->width),
37 /* negative height means bmp is stored from top to bottom */
38 .biHeight = end_htole32( - d->height),
39 .biPlanes = end_htole32(1),
40 .biBitCount = end_htole32(d->bytesperpixel * 8),
41 .biCompression = 0,
42 .biSizeImage = 0,
43 .biXPelsPerMeter = end_htole32(0xb11),
44 .biYPelsPerMeter = end_htole32(0xb11),
46 fwrite(&hdr, 1, sizeof hdr, f);
47 pad_bmp(d);
48 fwrite(d->data, 1, d->data_size, f);
49 fclose(f);
50 } else {
51 fprintf(stderr, "error opening %s\n", name);
55 #endif