[英]reading and writtinng BMP images
我想加載和寫入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,然后讀取圖像本身的數據,為什么它不起作用? 我忽略了什么嗎? 感謝幫助!
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;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.