我试图弄清楚如何在C++ VS中创建位图文件。目前,我已经输入了文件名并添加了“.bmp”扩展名来创建文件。我想知道如何通过将文件设置为不同的颜色或图案(例如,像棋盘一样)来更改像素,这是我所拥有的功能,并且我相信每次必须发送3个不同的字节以建立像素的颜色。

void makeCheckerboardBMP(string fileName, int squaresize, int n) {
    ofstream ofs;
    ofs.open(fileName + ".bmp");
    writeHeader(ofs, n, n);

    for(int row = 0; row < n; row++) {
        for(int col = 0; col < n; col++) {

            if(col % 2 == 0) {
                ofs << 0;
                ofs << 0;
                ofs << 0;
            } else {
                ofs << 255;
                ofs << 255;
                ofs << 255;
            }
        }
    }
}

void writeHeader(ostream& out, int width, int height){
    if (width % 4 != 0) {
        cerr << "ERROR: There is a windows-imposed requirement on BMP that the width be a
multiple of 4.\n";
        cerr << "Your width does not meet this requirement, hence this will fail.  You can fix
this\n";
        cerr << "by increasing the width to a multiple of 4." << endl;
        exit(1);
    }

    BITMAPFILEHEADER tWBFH;
    tWBFH.bfType = 0x4d42;
    tWBFH.bfSize = 14 + 40 + (width*height*3);
    tWBFH.bfReserved1 = 0;
    tWBFH.bfReserved2 = 0;
    tWBFH.bfOffBits = 14 + 40;

    BITMAPINFOHEADER tW2BH;
    memset(&tW2BH,0,40);
    tW2BH.biSize = 40;
    tW2BH.biWidth = width;
    tW2BH.biHeight = height;
    tW2BH.biPlanes = 1;
    tW2BH.biBitCount = 24;
    tW2BH.biCompression = 0;

    out.write((char*)(&tWBFH),14);
    out.write((char*)(&tW2BH),40);
}

最佳答案

鉴于您的writeHeader正确实现,这几乎是正确的。您需要修复2个问题:

  • 您正在为每个颜色通道编写一个int。应该是一个字节。您需要将文字转换为unsigned char
  • 位图中的扫描线需要与DWORD对齐。在col上进行内部循环之后,您需要写出其他字节来解决这个问题,除非该行的字节大小为4的倍数。
  • 07-24 09:44
    查看更多