我在用 C++ 读取位图文件时遇到了麻烦。我的代码仅在行填充等于 3 个字节时才有效。任何其他填充都会产生奇怪的事情 - 有时我无法读取输出文件,有时我可以打开它,但它看起来像垃圾并且具有不同的宽度和高度。
这是我从位图文件中读取数据的函数:
void read_bmp(ImageFile* Image, const char* filename){
FILE* pFile;
unsigned char* buffer;
unsigned int bufferSize, offset_bitmapData, counter_PixelCounter=0, offset_paddingSum=0;
pFile = fopen(filename, "rb");
if(pFile==NULL) throw ERR_FILE_DOES_NOT_EXIST;
fseek(pFile, 0, SEEK_SET);
bufferSize = 54;
buffer = new unsigned char[bufferSize];
if(fread(buffer, sizeof(char), bufferSize, pFile)!=bufferSize) throw ERR_FILE_READING_ERROR;
if(readBytes_int(0, 2, buffer)!=0x4D42) throw ERR_NO_BMP_HEADER;
offset_bitmapData = readBytes_int(0x0A, 4, buffer);
Image->ImageWidth = readBytes_int(0x12, 4, buffer);
Image->ImageHeight = readBytes_int(0x16, 4, buffer);
Image->FileSize = readBytes_int(0x02, 4, buffer);
Image->bbpInfo = readBytes_int(0x1C, 2,buffer);
Image->Padding = (4 - (Image->ImageWidth*3)%4)%4;
cout<<"width "<<Image->ImageWidth<<endl;
cout<<"padding "<<(int)Image->Padding<<endl;
if(readBytes_int(0x0E, 4, buffer)!=40) throw ERR_NO_BITMAPINFOHEADER;
delete[] buffer;
bufferSize = Image->ImageWidth * Image->ImageHeight * 3 + Image->ImageHeight * Image->Padding;
buffer = new unsigned char[bufferSize];
if(buffer==NULL) throw ERR_BAD_ALLOC;
fseek(pFile, offset_bitmapData, SEEK_SET);
if(fread(buffer, sizeof(char), bufferSize, pFile)!=bufferSize) throw ERR_FILE_READING_ERROR;
fclose(pFile);
Image->PixelArray = new unsigned char**[Image->ImageHeight];
counter_PixelCounter = 0;
for(int height = Image->ImageHeight-1; height >= 0; height--)
{
Image->PixelArray[height] = new unsigned char*[Image->ImageWidth];
for(int width = 0; width < Image->ImageWidth; width++)
{
Image->PixelArray[height][width] = new unsigned char[3];
Image->PixelArray[height][width][0] = (unsigned char)readBytes_int((counter_PixelCounter ) * 3 + offset_paddingSum + 2, 1, buffer);
Image->PixelArray[height][width][1] = (unsigned char)readBytes_int((counter_PixelCounter ) * 3 + offset_paddingSum + 1, 1, buffer);
Image->PixelArray[height][width][2] = (unsigned char)readBytes_int((counter_PixelCounter ) * 3 + offset_paddingSum, 1, buffer);
counter_PixelCounter++;
}
offset_paddingSum += Image->Padding;
}
cout<<counter_PixelCounter<<endl;
cout<<"File loaded successfully\n";
}