从bmp文件读取字节 [英] Reading bytes from bmp file
问题描述
我如何从一个bmp文件使用C读取字节?
How do I read the bytes from a bmp file using C?
推荐答案
下面是一个通用的骨架只加载一个二进制文件,并返回一个指向第一个字节。这归结为fopen()函数后跟FREAD(),不过是一个...有点冗长。有没有错误处理,但错误检查,我相信这code是正确的。这code将拒绝空文件(其中,顾名思义,不包含任何数据无论如何加载)。
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);
}
}
}
您可以轻松地添加了code解析BMP头,即使用在其他的答案提供的链接。
You can easily add the code to parse the BMP header to this, using links provided in other answers.
这篇关于从bmp文件读取字节的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!