Using bitmaps in C (really basic)
I don't like C, but sometimes I have to use it, and this was one of those times. Here's a quick explanation on how to read a 24 bit bitmap in C:
The code is here](bitmap.c), it takes a bitmap and prints it out as ASCII, like the picture at the right.
Header
Basically you want to open the file as binary for reading: `C fp = fopen(bmpFile,"rb")`c and find the useful values in the header. More information about the header can be found [here](http://www.fortunecity.com/skyscraper/windows/364/bmpffrmt.html).
Here's how I read through the header, somewhat awkwardly putting the bits I don't care about into a char* called junk:
word filesize, width, height, bitsperpixel;
fread(&filesize, 4, 1, fp);
fread(junk,12,1,fp); //ignore some of the file
fread(&width, 4, 1, fp);
fread(&height, 4, 1, fp);
fread(junk,2,1,fp); //ignore some of the file
fread(&bitsperpixel, 2, 1, fp);
fread(junk, 24, 1, fp);//ignore some of the file
Problems
The bitmap format has each row padded out with zeros to be a multiple of 4. As in: `C int padding = (4-((3*width) % 4))%4; `c, which I addded to the loop that reads the rows.
Also the rows are upside down. Which is annoying.
I only print out the bitmap, I assume you that if you need it, you know how to use `Cmalloc`c to proceed to actually do something with the picture.
bitmap1.zip is a zip containing the source, some test BMPs and a compiled EXE.
Code
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
typedef unsigned char byte;
typedef unsigned short word;
typedef unsigned long dword;
int main(int argc, char *argv[]) {
FILE *fp;
char *bmpFile;
char junk[255];
if(argc==2) {
bmpFile = argv[1];
} else {
bmpFile = "t.bmp";
}
if ((fp = fopen(bmpFile,"rb")) == NULL) {
printf("Can't find file: %s.\n",bmpFile
); exit(1);
}
/* minor error handling */
if (fgetc(fp)!='B' || fgetc(fp)!='M') {
fclose(fp);
printf("Invlaid file: %s.\n",bmpFile
); exit(1);
}
word filesize, width, height, bitsperpixel;
word r,g,b,pixel;
fread(&filesize, 4, 1, fp);
fread(junk,12,1,fp); //ignore some of the file
fread(&width, 4, 1, fp);
fread(&height, 4, 1, fp);
printf("Size: %d,[%dx%d]\n",filesize
,width
,height
); fread(junk,2,1,fp); //ignore some of the file
fread(&bitsperpixel, 2, 1, fp);
if (bitsperpixel<24) {
fclose(fp);
printf("This is designed for 24 bit bitmaps, %s has %d.\n",bmpFile
,bitsperpixel
); exit(1);
}
fread(junk, 24, 1, fp);
int x,y;
//the format pretends all rows are divisible by 4
int padding = (4-((3*width) % 4))%4;
//the image is stored upside down:
for(y=0;y<height;y++) {
for(x=0;x<width;x++) {
r=b=g=0;
fread(&b, 1, 1, fp);
fread(&g, 1, 1, fp);
fread(&r, 1, 1, fp);
pixel = g;
else if(pixel
>150) printf("X"); else if(pixel
>100) printf("+"); else if(pixel
>50) printf(":");
}
fread(junk, padding,1,fp);
}
}