gpt4 book ai didi

c++ - 读取bmp文件头大小

转载 作者:行者123 更新时间:2023-11-28 01:42:49 25 4
gpt4 key购买 nike

我正在尝试查找 bmp 文件的文件大小、文件头大小宽度和高度。我研究了bmp文件的格式和文件中字节的排列。当我尝试此代码时,它显示不同文件的宽度和高度错误。到目前为止,我已经对三张图片进行了尝试。这一张图片给出了正确的测量结果。

Woman

这个没有:

enter image description here

我不明白哪里出错了,但是位深度显示了所有三张图片的正确值。

这是我的代码:

#include<iostream>
#include<fstream>
#include<math.h>

using namespace std;


int main() {
ifstream inputfile("bmp.bmp",ios::binary);
char c; int imageheader[1024];

double filesize=0; int width=0; int height=0;int bitCount = 0;

for(int i=0; i<1024; i++) {
inputfile.get(c); imageheader[i]=int(c);
}

filesize=filesize+(imageheader[2])*pow(2,0)+(imageheader[3])*pow(2,8)+(imageheader[4])*pow(2,16)+(imageheader[5])*pow(2,24);

cout<<endl<<endl<<"File Size: "<<(filesize/1024)<<" Kilo Bytes"<<endl;

width=width+(imageheader[18])*pow(2,0)+(imageheader[19])*pow(2,8)+(imageheader[20])*pow(2,16)+(imageheader[21])*pow(2,24);

cout<<endl<<"Width: "<<endl<<(width)<<endl;

height=height+(imageheader[22])*pow(2,0)+(imageheader[23])*pow(2,8)+(imageheader[24])*pow(2,16)+(imageheader[25])*pow(2,24);
cout<<endl<<"Height: "<<endl<<(height)<<endl;

bitCount=bitCount+(imageheader[28])*pow(2,0)+(imageheader[29])*pow(2,8);
cout<<endl<<"Bit Depth: "<<endl<<(bitCount)<<endl;
}

最佳答案

让我们首先以一系列字节而非整数的形式读取 BMP header 。为了使这段代码真正可移植,我们将使用 <stdint>类型。

#include <fstream>
#include <stdint.h>

int main()
{

ifstream inputfile("D:/test.bmp", ios::binary);
uint8_t headerbytes[54] = {};

inputfile.read((char*)headerbytes, sizeof(headerbytes));

既然我们已经在内存中获得了作为字节数组的 header ,我们可以简单地将每个 header 字段的内存地址转换回整数。引用 wikipedia page对于 bmp 和 the layout diagram .

    uint32_t filesize = *(uint32_t*)(headerbytes+2);
uint32_t dibheadersize = *(uint32_t*)(headerbytes + 14);
uint32_t width = *(uint32_t*)(headerbytes + 18);
uint32_t height = *(uint32_t*)(headerbytes + 22);
uint16_t planes = *(uint16_t*)(headerbytes + 26);
uint16_t bitcount = *(uint16_t*)(headerbytes + 28);

现在,精明的代码读者会认识到 BMP header 的各个字段是以小端格式存储的。并且上面的代码依赖于您拥有 x86 处理器或字节布局为 Little Endian 的任何其他体系结构。 .在大端机器上,您必须应用变通方法将上述每个变量从 LE 转换为 BE。

关于c++ - 读取bmp文件头大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46504639/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com