【问题标题】:Reading bmp file and sending data to array读取 bmp 文件并将数据发送到数组
【发布时间】:2018-03-15 20:30:11
【问题描述】:

我正在尝试获取有关 bmp 文件的一些信息。例如,我想要得到的一件事是文件的高度。为此,我使用以下代码行:

char params[size];
fread (params, 1, size, bmpfile);
*height = *((int *)(params + 22));

但是,每当我打印高度时,我都会得到 0。为什么我做错了,我应该改变什么?提前感谢您的帮助!

【问题讨论】:

  • 我怀疑这与我的恐惧有关,但我不确定该怎么办
  • 查看任何格式说明。看来您正在阅读“颜色平面的数量”,而不是高度。 (并且您正在假设它与您的系统匹配的字节顺序,这可能会在另一个系统或其他格式上咬住您。)

标签: c fread bmp


【解决方案1】:

fread (params, 1, size, bmpfile);

第二个参数应该是元素大小,第三个参数应该是元素个数。你应该把它写成

fread (params, size, 1, bmpfile);

虽然结果相同,但fread 的返回值不同。其余基本正确。添加错误检查以查找问题:

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

int main(void)
{
    FILE *bmpfile = fopen("c:\\test\\test.bmp", "rb");
    if(!bmpfile)
    {
        printf("file not found\n");
        return 0;
    }

    char params[54] = { 0 };
    int result = fread(params, sizeof(params), 1, bmpfile);
    if(result != 1)
    {
        printf("not bitmap file\n");
        return 0;
    }

    if(strncmp(params, "BM", 2) != 0)
    {
        printf("not bitmap file\n");
        return 0;
    }

    int width = *(int*)(params + 18);
    int height = *(int*)(params + 22);
    int bitcount = *(int*)(params + 28);
    printf("%d %d %d\n", width, height, bitcount);
    fclose(bmpfile);
    return 0;
}

【讨论】:

    猜你喜欢
    • 2022-10-06
    • 1970-01-01
    • 2012-03-30
    • 2016-11-22
    • 2021-05-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-12-14
    相关资源
    最近更新 更多