C++位图编辑

C++ bitmap editing

本文关键字:编辑 位图 C++      更新时间:2023-10-16

我正在尝试打开一个位图文件,对其进行编辑,然后将编辑后的版本另存为新文件。这最终会弄乱使用隐写术。我现在正在尝试保存位图信息,但保存的文件无法打开。编译或运行时没有错误。它打开正常,其余功能工作。

void cBitmap::SaveBitmap(char * filename)
{
    // attempt to open the file specified
    ofstream fout;
    // attempt to open the file using binary access
    fout.open(filename, ios::binary);
    unsigned int number_of_bytes(m_info.biWidth * m_info.biHeight * 4);
    BYTE red(0), green(0), blue(0);
    if (fout.is_open())
    {
        // same as before, only outputting now
        fout.write((char *)(&m_header), sizeof(BITMAPFILEHEADER));
        fout.write((char *)(&m_info), sizeof(BITMAPINFOHEADER));
        // read off the color data in the bass ackwards MS way
        for (unsigned int index(0); index < number_of_bytes; index += 4)
        {
            red = m_rgba_data[index];
            green = m_rgba_data[index + 1];
            blue = m_rgba_data[index + 2];
            fout.write((const char *)(&blue), sizeof(blue));
            fout.write((const char *)(&green), sizeof(green));
            fout.write((const char *)(&red), sizeof(red));
        }

    }
    else
    {
        // post file not found message
        cout <<filename << " not found";
    }
    // close the file
    fout.close();
}

您缺少每个 RGB 行后面的填充字节。 每行必须是 4 个字节的倍数。

另外,您应该编写 24 位或 32 位 bmp 文件吗? 如果您正在编写 24 位,则只是缺少填充。 如果您正在写入 32 位,那么您将缺少每个额外的字节 (alpha)。 没有足够的信息来修复您的代码示例,而不是编写一个支持所有可能选项的完整 bmp 编写器。