// io_bmp.c
#include <stdio.h>
#include "io_bmp.h"
struct BMP_HEADER {
unsigned char BM[2];
unsigned long f_sz;
unsigned long pd0;
unsigned long p_ofs;
unsigned long bhs;
long w;
long h;
unsigned short pl;
unsigned short bit;
unsigned long cmp;
unsigned long isz;
unsigned long xppm;
unsigned long yppm;
unsigned long cltu;
unsigned long clti;
} __attribute__ ((packed));
void read_BMP(struct BMP* a, char* file_name)
{
FILE* fp = fopen(file_name, "rb");
struct BMP_HEADER hd;
fseek(fp, 0, SEEK_SET);
fread(&hd, sizeof(struct BMP_HEADER), 1, fp);
a->w = hd.w;
a->h = hd.h;
const unsigned long p_ofs = hd.p_ofs;
int q = 4 - ((a->w * 3) % 4);
q = (q == 4) ? 0 : q;
struct PIXEL* p;
int j = a->h; while (j-- > 0) {
fseek(fp, p_ofs + (((a->w * 3) + q) * j), SEEK_SET);
p = a->p + (a->w * j);
fread(p, sizeof(struct PIXEL), a->w, fp);
}
}
void write_BMP(struct BMP* a, char* file_name)
{
FILE* fp=fopen(file_name, "wb");
int q = 4 - ((a->w * 3) % 4);
q = (q == 4) ? 0 : q;
const unsigned long p_ofs=54;
const unsigned long i_sz=((a->w * 3) + q) * a->h;
struct BMP_HEADER hd = {
'B','M',
p_ofs + i_sz,
0,
p_ofs,
40,
a->w,
a->h,
1,
24,
0,
i_sz, 3780, 3780,
0, 0
};
fseek(fp, 0, SEEK_SET);
fwrite(&hd, sizeof(struct BMP_HEADER), 1, fp);
struct PIXEL* p;
int j = a->h; while (j-- > 0) {
fseek(fp, p_ofs + ((a->w * 3) + q) * j, SEEK_SET);
p = a->p + (a->w * j);
fwrite(p, sizeof(unsigned char), (a->w * 3) + q, fp);
}
}