Skip to content

Instantly share code, notes, and snippets.

@tim37021
Created July 11, 2016 13:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tim37021/63d36d6d0c4c8e3b3b370efc9dbddd7d to your computer and use it in GitHub Desktop.
Save tim37021/63d36d6d0c4c8e3b3b370efc9dbddd7d to your computer and use it in GitHub Desktop.
Mini C BMP Loader
// mini bmp loader written by HSU YOU-LUN
unsigned char *load_bmp(const char *bmp, unsigned int *width, unsigned int *height, unsigned short int *bits)
{
unsigned char *result=nullptr;
FILE *fp = fopen(bmp, "rb");
if(!fp)
return nullptr;
char type[2];
unsigned int size, offset;
// check for magic signature
fread(type, sizeof(type), 1, fp);
if(type[0]==0x42 || type[1]==0x4d){
fread(&size, sizeof(size), 1, fp);
// ignore 2 two-byte reversed fields
fseek(fp, 4, SEEK_CUR);
fread(&offset, sizeof(offset), 1, fp);
// ignore size of bmpinfoheader field
fseek(fp, 4, SEEK_CUR);
fread(width, sizeof(*width), 1, fp);
fread(height, sizeof(*height), 1, fp);
// ignore planes field
fseek(fp, 2, SEEK_CUR);
fread(bits, sizeof(*bits), 1, fp);
unsigned char *pos = result = new unsigned char[size-offset];
fseek(fp, offset, SEEK_SET);
while(size-ftell(fp)>0)
pos+=fread(pos, 1, size-ftell(fp), fp);
}
fclose(fp);
return result;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment