在C 中读取并编写BMP文件

read and write a bmp file in c++

本文关键字:BMP 文件 读取      更新时间:2023-10-16

我正在尝试在C 中读取和编写一个BMP文件。输出文件是创建但不是打开的,它的大小为257kb,而输入文件为258kb.i首先读取并写入14个字节标头文件,40个字节imageheader文件,然后是512*512像素,这是我的代码,任何人都可以帮忙

#include <iostream>
#include <fstream>
#include <cmath>
using namespace std;
int main()
{
ifstream iFile;
char ch;
iFile.open("lena.bmp",ios::binary);
ofstream oFile;
oFile.open("lena3.bmp",ios::binary);
//int headerImageHeader=54;
// int imageHeader=40;
int fs[54];
//int ihs[imageHeader];
int tfs[54];
int pixel[512][512];
if(iFile.is_open() && oFile.is_open())
{
   for(int i=0;i<54;i++)
    {
        iFile.get(ch);
        fs[i]=ch;
        cout<<fs[i]<<"  ";
        char p;
        p=fs[i];
        oFile<<p;
    }
for(int w=0;w<512;w++)
    {
        for(int h=0;h<512;h++)
        {
            iFile.get(ch);
            pixel[w][h]=ch;
            //cout<<pixel[w][h]<<;
            char pi=pixel[w][h];
            oFile<<pi;
        }
    }
   oFile.close();
   iFile.close();
}
else cout << "Unable to open file"<<endl;
return 0;

}

您的代码有多个问题。基本上,BMP文件中的像素存储并不是那么简单。它取决于BMP的类型(例如Monochrome Bitmap16 Color Bitmap256 Color Bitmap24-bit Bitmap等)。

有两个选项可以读取一个位图文件并将其写入另一个位图文件。a)从源文件中读取每个字节并在目标文件中写入b)了解Bitmap存储格式并相应地编写代码。

对于选项b),请访问良好的来源。

总而言之,像素阵列存储的计算(大小)为:

PixelArraySize = RowSize x ImageHeight

其中ImageHeight是像素中图像的高度。排名计算为:

RowSize = [(BitsPerPixelxImageWidth + 31) / 32 ]x4