0

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";
}
4

2 に答える 2

0

.BMP ファイルには、ファイルのアドレス 0x22 のパディングのサイズを記述するための 4 バイトがあります。

それを読んでパディングをスキップできます。この質問と回答も参照してください: C++: .bmp to byte array in a file

于 2013-10-25T07:59:31.647 に答える