2

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

4

5 回答 5

5

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.

于 2009-06-26T07:55:52.373 回答
3

按照其他人的建议使用 fopen 和 fread。对于 bmp 标头的格式,请查看此处

于 2009-06-26T07:13:10.803 回答
2

fopen 后跟 fread

于 2009-06-26T07:05:10.523 回答
1

ImageMagick支持 BMP。您可以使用两种 C API 中的任何一种,低级MagickCore或更高级别的Magick Wand

于 2009-06-26T07:05:01.787 回答
0

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.

于 2009-06-26T08:38:11.040 回答