BMP文件行填充问题

7

我正在尝试在C++代码中导出一个.bmp文件,现在已经有了一部分的成果,但是还有一个重要的问题:行填充。我不是100%确定行填充的工作原理,但我知道我需要它。我的算法除了填充以外都已经成功,我手动在导出的图像上在十六进制编辑器中添加了填充,并且它奏效了。但是如何添加填充呢?这是我的代码:

//Size of the file in bytes
    int fileSize = 54 + (3 * width * height);

    //The sections of the file
    unsigned char generalHeader[14] = {'B','M',0,0, 0,0,0,0, 0,0,54,0, 0,0};
    unsigned char DIBHeader[40]     = {40,0,0,0, 0,0,0,0, 0,0,0,0, 1,0,24,0, 0,0,0,0, 0,0,0,0, 0,0,0,0, 0,0,0,0, 0,0,0,0, 0,0,0,0};
    unsigned char pixelArray[1000000];
    unsigned char bmpPad[3] = {0, 0, 0};

    //Set the binary portion of the generalHeader, mainly just file size
    generalHeader[2] = (unsigned char)(fileSize);
    generalHeader[3] = (unsigned char)(fileSize >> 8);
    generalHeader[4] = (unsigned char)(fileSize >> 16);
    generalHeader[5] = (unsigned char)(fileSize >> 24);

    //The binary variable portion of the DIB header
    DIBHeader[4]  = (unsigned char)(width);
    DIBHeader[5]  = (unsigned char)(width >> 8);
    DIBHeader[6]  = (unsigned char)(width >> 16);
    DIBHeader[7]  = (unsigned char)(width >> 24);
    DIBHeader[8]  = (unsigned char)(height);
    DIBHeader[9]  = (unsigned char)(height >> 8);
    DIBHeader[10] = (unsigned char)(height >> 16);
    DIBHeader[11] = (unsigned char)(height >> 24);

    //Loop through all width and height places to add all pixels


    int counter = 0;
    for(short j = height; j >= 0; j--)
    {
        for(short i = 0; i < width; i++)
        {
            //Add all 3 RGB values
            pixelArray[counter] = pixelColour[i][j].red;
            pixelArray[counter] = pixelColour[i][j].green;
            pixelArray[counter] = pixelColour[i][j].blue;
            counter++;
        }
    }

    //Open it
    ofstream fileWorking(fileName);

    //Write the sections
    fileWorking.write((const char*)generalHeader, 14);
    fileWorking.write((const char*)DIBHeader, 40);
    fileWorking.write((const char*)pixelArray, 3 * width * height);

    //NO MEMORY LEAKS 4 ME
    fileWorking.close();

pixelColour是一个结构体数据类型,包含三种颜色,所有颜色的类型都是unsigned char。非常感谢您的帮助!

1个回答

7

在您的情况下,每一行必须是4字节(32位)的倍数。

int pad = 0; // Set pad byte count per row to zero by default.
// Each row needs to be a multiple of 4 bytes.  
if ((width * 3) % 4 != 0) pad = 4 - ((width * 3) % 4); // 4 - remainder(width * 3 / 4).

填充值可以包含任何内容,但最好将它们设置为 0。当您完成每行的写入时,只需在写入下一行之前写入附加的 pad 个零(字节)。

for(short j = height; j >= 0; j--) {
    for(short i = 0; i < width; i++) {
        //Add all 3 RGB values
        pixelArray[counter++] = pixelColour[i][j].red; // Need to advance counter.
        pixelArray[counter++] = pixelColour[i][j].green;
        pixelArray[counter++] = pixelColour[i][j].blue;
    }
    for (int padVal = 0; padVal < pad; padVal++) pixelArray[counter++] = 0; // Pad.
}

最后,您需要编写一个更大的文件大小:

fileWorking.write((const char*) pixelArray, (3 * width + pad) * height);

非常感谢你,伙计!我真的很感激你的帮助! - null

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接