读取和写入BMP图像

问题描述 投票:0回答:1

我想加载和写入BMP图像,我只是试图加载字节并将其写回到文件,我的代码如下:

unsigned char* readBMP(char* filename)
{
    int i;
    FILE* f = fopen(filename, "rb");
    unsigned char info[54];
    fread(info, sizeof(unsigned char), 54, f); // read the 54-byte header

    // extract image height and width from header
    int width = *(int*)&info[18];
    int height = *(int*)&info[22];

    int size = 3 * width * height;
    unsigned char* data = new unsigned char[size]; // allocate 3 bytes per pixel
    fread(data, sizeof(unsigned char), size, f); // read the rest of the data at once
    fclose(f);

    ofstream fout;
    fout.open("konik2.bmp", ios::binary | ios::out);
    fout.write((char*) &info, sizeof(info));
    fout.write((char*) &data, sizeof(data));

    fout.close();
    return data;
}

但是输出文件已损坏,请使用hexeditor打开它,我看到有完全不同的字节。我所做的就是先读取metaData,然后读取图像本身的数据,为什么它不起作用?我忽略了什么吗?感谢您的帮助!

c++ image bmp
1个回答
0
投票
fout.write((char*)&data, sizeof(data));

您要写data而不是&data。并使用size代替sizeof(data)(只有4或8)

size应该被填充,这样“以字节为单位的宽度”是4的倍数。

您要检查位图文件(bpp)的位数,以确保它适用于任何位图。

unsigned char* readBMP(char* filename)
{
    FILE* f = fopen(filename, "rb");
    unsigned char info[54];
    fread(info, sizeof(unsigned char), 54, f); // read the 54-byte header

    // extract image height and width from header
    int width = *(int*)&info[18];
    int height = *(int*)&info[22];
    int bpp = *(int*)&info[28];

    int size = ((width * bpp + 31) / 32) * 4 * height; //<==== change
    unsigned char* data = new unsigned char[size]; 
    fread(data, sizeof(unsigned char), size, f); 
    fclose(f);

    ofstream fout;
    fout.open("c:\\test\\_out.bmp", ios::binary);
    fout.write((char*)&info, sizeof(info));
    fout.write((char*)data, size); //<==== change

    fout.close();
    return data;
}
© www.soinside.com 2019 - 2024. All rights reserved.