简体   繁体   中英

Reading bytes from bmp file

如何使用C读取bmp文件中的字节?

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.

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

fopen接着是fread

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM