2
votes

How do I read the bytes from a bmp file using C?

5

5 Answers

5
votes

Here's a general-purpose skeleton to just load a binary file, and return a pointer to the first byte. This boils down to "fopen() followed by fread()", but is a ... bit more verbose. There's no error-handling, although errors are checked for and I believe this code to be correct. This code will reject empty files (which, by definition, don't contain any data to load anyway).

#include <stdio.h>
#include <stdlib.h>

static int file_size(FILE *in, size_t *size)
{
  if(fseek(in, 0, SEEK_END) == 0)
  {
    long len = ftell(in);
    if(len > 0)
    {
      if(fseek(in, 0, SEEK_SET) == 0)
      {
        *size = (size_t) len;
        return 1;
      }
    }
  }
  return 0;
}

static void * load_binary(const char *filename, size_t *size)
{
  FILE *in;
  void *data = NULL;
  size_t len;

  if((in = fopen(filename, "rb")) != NULL)
  {
    if(file_size(in, &len))
    {
      if((data = malloc(len)) != NULL)
      {
        if(fread(data, 1, len, in) == len)
          *size = len;
        else
        {
          free(data);
          data = NULL;
        }
      }
    }
    fclose(in);
  }
  return data;
}

int main(int argc, char *argv[])
{
  int i;

  for(i = 1; argv[i] != NULL; i++)
  {
    void *image;
    size_t size;

    if((image = load_binary(argv[i], &size)) != NULL)
    {
      printf("Loaded BMP from '%s', size is %u bytes\n", argv[i], (unsigned int) size);
      free(image);
    }
  }
}

You can easily add the code to parse the BMP header to this, using links provided in other answers.

3
votes

Use fopen and fread as suggested by others. For the format of the bmp header take a look here

2
votes

fopen followed by fread

1
votes

ImageMagick supports BMP. You can use either of two C APIs, the low-level MagickCore or the more high level Magick Wand.

0
votes

make sure this file is not compressed using RLE method. otherwise, you'll have to read from the file and dump into a buffer to reconstruct the image, after reading the header file and knowing it's dimensions.