c++从头开始制作位图时遇到问题

c++ trouble with making a bitmap from scratch

本文关键字:遇到 问题 位图 从头开始 c++      更新时间:2023-10-16

我正在尝试从头开始制作位图。我有一个RGB值的BYTE数组(具有已知大小),我想生成一个HBITMAP。

为了进一步澄清,我使用的字节数组纯粹是RGB值。

我已经确保所有变量都设置正确,并且我认为问题与lpvBits有关。在过去的几天里,我一直在为此做大量的研究,但我一直找不到任何对我有意义的东西

出于测试目的,width = 6height = 1

代码:

HBITMAP RayTracing::getBitmap(void){
    BYTE * bytes = getPixels();
    void * lpvBits = (void *)bytes;
    HBITMAP hBMP = CreateBitmap(width, height, 1, 24, lpvBits);
    return hBMP;
}
BYTE * RayTracing::getPixels(void){
    Vec3 * vecs = display.getPixels();
    BYTE * bytes;
    bytes = new BYTE[(3 * width * height)];
    for (unsigned int i = 0; i < (width * height); i++){
        *bytes = static_cast<BYTE>(vecs->x);
        bytes++;
        *bytes = static_cast<BYTE>(vecs->y);
        bytes++;
        *bytes = static_cast<BYTE>(vecs->z);
        bytes++;
        vecs++;
    }
    return bytes;
}

您需要正确地对数组进行双字对齐,使每行都是4个字节的偶数倍,然后在填充数组时跳过这些字节:

HBITMAP RayTracing::getBitmap(void)
{
    BYTE * bytes = getPixels();
    HBITMAP hBMP = CreateBitmap(width, height, 1, 24, bytes);
    delete[] bytes;
    return hBMP;
}
BYTE * RayTracing::getPixels(void)
{
    Vec3 * vecs = display.getPixels(); // <-- don't forget to free if needed
    int linesize = ((3 * width) + 3) & ~3; // <- 24bit pixels, width number of pixels, rounded to nearest dword boundary
    BYTE * bytes = new BYTE[linesize * height];
    for (unsigned int y = 0; y < height; y++)
    {
        BYTE *line = &bytes[linesize*y];
        Vec3 *vec = &vecs[width*y];
        for (unsigned int x = 0; x < width; x++)
        {
            *line++ = static_cast<BYTE>(vec->x);
            *line++ = static_cast<BYTE>(vec->y);
            *line++ = static_cast<BYTE>(vec->z);
            ++vec;
        }
    }
    return bytes;
}

CreateBitmap的第三个参数应该是3,而不是1。有三种颜色平面:红色、绿色和蓝色。

此外,如果将高度设置为大于1的任何值,则需要用零填充每行像素,以使宽度为4的倍数。因此,对于6x2图像,在为第一行保存6*3字节后,您需要保存两个零字节,使该行长20字节。