c++改变位图中的值

c++ changing the values in a bitmap

本文关键字:位图 改变 c++      更新时间:2023-10-16

我试图改变像素在"cool.bmp"图像和绘制它到一个窗口改变。到目前为止,所有的代码都正确执行,但当我改变像素数组中的字节时,图像不会改变(是的,我正在重新绘制屏幕)。

   case WM_CREATE:// runs once on creation of window
            hBitmap = (HBITMAP)LoadImage(NULL, L"cool.bmp", IMAGE_BITMAP, 0, 0, LR_LOADFROMFILE );
            if(hBitmap == NULL)
                ::printToDebugWindow("Error: loading bitmapn");
            else
            {
                BYTE* b = ::getPixArray(hBitmap);
                for(int i = 0; i< 1920*1080*4; i+=4) // problem!! 
                {
                    b[i] = 255;//blue
                    b[i+1] = 255;//green
                    b[i+2] = 255;//red
                    b[i+3] = 255;//alpha
                }

//从位图图像中获取pixArray的方法

BYTE* getPixArray(HBITMAP hBitmap)
{
    HDC hdc,hdcMem;
    hdc = GetDC(NULL);
    hdcMem = CreateCompatibleDC(hdc); 
    BITMAPINFO MyBMInfo = {0};
    MyBMInfo.bmiHeader.biSize = sizeof(MyBMInfo.bmiHeader);
    // Get the BITMAPINFO structure from the bitmap
    if(0 == GetDIBits(hdcMem, hBitmap, 0, 0, NULL, &MyBMInfo, DIB_RGB_COLORS))
    {
        ::printToDebugWindow("FAILn");
    }
    // create the bitmap buffer
    BYTE* lpPixels = new BYTE[MyBMInfo.bmiHeader.biSizeImage];
    MyBMInfo.bmiHeader.biBitCount = 32;  
    MyBMInfo.bmiHeader.biCompression = BI_RGB;  
    MyBMInfo.bmiHeader.biHeight = (MyBMInfo.bmiHeader.biHeight < 0) ? (-MyBMInfo.bmiHeader.biHeight) : (MyBMInfo.bmiHeader.biHeight); 
    // get the actual bitmap buffer
    if(0 == GetDIBits(hdcMem, hBitmap, 0, MyBMInfo.bmiHeader.biHeight, (LPVOID)lpPixels, &MyBMInfo, DIB_RGB_COLORS))
    {
        ::printToDebugWindow("FAILn");
    }
    return lpPixels;
}

上面的代码看起来像这样应该改变图像中的所有像素为白色?但是没有效果。

BYTE* b = ::getPixArray(hBitmap);
                for(int i = 0; i< 1920*1080*4; i+=4) // problem!! 
                {
                    b[i] = 255;//blue
                    b[i+1] = 255;//green
                    b[i+2] = 255;//red
                    b[i+3] = 255;//alpha
                }

GetDIBits()只是将位图复制到缓冲区。您需要在修改缓冲区后使用SetDIBits()将其设置回HBITMAP