-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbitmap.c
More file actions
56 lines (47 loc) · 1.82 KB
/
bitmap.c
File metadata and controls
56 lines (47 loc) · 1.82 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
#include <stdio.h>
#include <stdlib.h>
#include "bitmap.h"
Bitmap *BitmapNewImage(uint16_t width, uint16_t height) {
Bitmap *bitmap;
bitmap = (Bitmap *)calloc(1, sizeof(*bitmap));
uint32_t headerSize = sizeof(BITMAPFILEHEADER) + sizeof(BITMAPCOREHEADER);
uint32_t rowSize = sizeof(RGBTRIPLE) * width;
// NOTE: Each row in the Pixel array is padded to a multiple of 4 bytes in size.
if (rowSize % 4) {
rowSize += 4 - rowSize % 4;
}
uint32_t size = rowSize * height;
bitmap->fileHeader = (BITMAPFILEHEADER){BMP_MAGIC, headerSize + size, 0, 0, headerSize};
bitmap->dibHeader = (BITMAPCOREHEADER){12, width, height, 1, 24};
bitmap->pixels = (RGBTRIPLE *)calloc(1, size);
return bitmap;
}
bool BitmapDestroy(Bitmap *bitmap) {
if (bitmap == NULL) {
#ifndef NDEBUG
fprintf(stderr, "%s: trying to free null pointer, ignored.\n", __FUNCTION_NAME__);
#endif
return false;
}
free(bitmap->pixels);
free(bitmap);
return true; // TODO: implement error handler
}
bool BitmapWriteFile(const Bitmap *bitmap, const char *filename) {
FILE *fp = fopen(filename, "w+");
fwrite(&bitmap->fileHeader, sizeof(BITMAPFILEHEADER), 1, fp);
fwrite(&bitmap->dibHeader, sizeof(BITMAPCOREHEADER), 1, fp);
fwrite(bitmap->pixels, bitmap->fileHeader.bfSize - bitmap->fileHeader.bfOffBits, 1, fp);
fclose(fp);
return true; // TODO: implement error handler
}
bool BitmapSetPixelColor(Bitmap *bitmap, uint16_t x, uint16_t y, const RGBTRIPLE *color) {
if (bitmap->dibHeader.bcWidth <= x || bitmap->dibHeader.bcHeight <= y) {
#ifndef NDEBUG
fprintf(stderr, "%s: Invalid pixel indices (x:%d<%d, y:%d<%d)\n", __FUNCTION_NAME__, x, bitmap->dibHeader.bcWidth, y, bitmap->dibHeader.bcHeight);
#endif
return false;
}
bitmap->pixels[x + bitmap->dibHeader.bcWidth * (bitmap->dibHeader.bcHeight - y - 1)] = *color;
return true;
}