#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct
BMPHeader
{
char
bfType[2];
int
bfSize;
int
bfReserved;
int
bfOffBits;
int
biSize;
int
biWidth;
int
biHeight;
short
biPlanes;
short
biBitCount;
int
biCompression;
int
biSizeImage;
int
biXPelsPerMeter;
int
biYPelsPerMeter;
int
biClrUsed;
int
biClrImportant;
};
int
read_bmp(
const
char
*filename,
int
*width,
int
*height, unsigned
char
*rgb)
{
fprintf
(stderr,
"Sorry, reading of .bmp files isn't supported yet.\n"
);
return
(0);
}
int
write_bmp(
const
char
*filename,
int
width,
int
height,
char
*rgb)
{
int
i, j, ipos;
int
bytesPerLine;
unsigned
char
*line;
FILE
*file;
struct
BMPHeader bmph;
bytesPerLine = (3 * (width + 1) / 4) * 4;
strcpy
(bmph.bfType,
"BM"
);
bmph.bfOffBits = 54;
bmph.bfSize = bmph.bfOffBits + bytesPerLine * height;
bmph.bfReserved = 0;
bmph.biSize = 40;
bmph.biWidth = width;
bmph.biHeight = height;
bmph.biPlanes = 1;
bmph.biBitCount = 24;
bmph.biCompression = 0;
bmph.biSizeImage = bytesPerLine * height;
bmph.biXPelsPerMeter = 0;
bmph.biYPelsPerMeter = 0;
bmph.biClrUsed = 0;
bmph.biClrImportant = 0;
file =
fopen
(filename,
"wb"
);
if
(file == NULL)
return
(0);
fwrite
(&bmph.bfType, 2, 1, file);
fwrite
(&bmph.bfSize, 4, 1, file);
fwrite
(&bmph.bfReserved, 4, 1, file);
fwrite
(&bmph.bfOffBits, 4, 1, file);
fwrite
(&bmph.biSize, 4, 1, file);
fwrite
(&bmph.biWidth, 4, 1, file);
fwrite
(&bmph.biHeight, 4, 1, file);
fwrite
(&bmph.biPlanes, 2, 1, file);
fwrite
(&bmph.biBitCount, 2, 1, file);
fwrite
(&bmph.biCompression, 4, 1, file);
fwrite
(&bmph.biSizeImage, 4, 1, file);
fwrite
(&bmph.biXPelsPerMeter, 4, 1, file);
fwrite
(&bmph.biYPelsPerMeter, 4, 1, file);
fwrite
(&bmph.biClrUsed, 4, 1, file);
fwrite
(&bmph.biClrImportant, 4, 1, file);
line =
malloc
(bytesPerLine);
if
(line == NULL)
{
fprintf
(stderr,
"Can't allocate memory for BMP file.\n"
);
return
(0);
}
for
(i = height - 1; i >= 0; i--)
{
for
(j = 0; j < width; j++)
{
ipos = 3 * (width * i + j);
line[3*j] = rgb[ipos + 2];
line[3*j+1] = rgb[ipos + 1];
line[3*j+2] = rgb[ipos];
}
fwrite
(line, bytesPerLine, 1, file);
}
free
(line);
fclose
(file);
return
(1);
}