c++ - 使用 winapi 加载/渲染位图问题

标签 c++ winapi bitmap

我正在使用 Windows API 直接将像素绘制到屏幕上(使用 CPU,而不是 GPU),并且在加载位图或渲染位图的方式上遇到了问题。这是相关代码(render_bmp 函数接受一个参数“buffer”,它是一个指向 win32_offscreen_buffer 的指针,这是显示在窗口中的全局缓冲区)
这是我的程序中图像的截图:
2 of hearts
这是源位图:
enter image description here
注意:这确实使用以下命令在 Windows 上使用 cl 编译器进行编译,假设您安装了 user32.lib 和 gdi32.lib:

cl -FC -Zi C:\stuff\reproduce.cpp user32.lib gdi32.lib
这是重现问题所需的最少代码。您需要将 WinMain 中的 char *filename 分配替换为计算机上 .bmp 的任何路径才能重现。
#include <windows.h>

struct win32_offscreen_buffer {
    BITMAPINFO info;
    void *memory;
    int width;
    int height;
    int bytes_per_pixel;
    int pitch;
};

struct window_dimension {
    int width;
    int height;
};

struct read_file_result {
    unsigned int contents_size;
    void *contents;
};

struct bitmap_result {
    BITMAPFILEHEADER *file_header;
    BITMAPINFOHEADER *info_header;
    unsigned int *pixels;
    unsigned int stride;
};

win32_offscreen_buffer global_buffer;
unsigned char should_quit = 0;  // BOOL

window_dimension get_window_dimension(HWND window) {
    RECT client_rect;
    GetClientRect(window, &client_rect);
    
    window_dimension result;
    
    result.width = client_rect.right - client_rect.left;
    result.height = client_rect.bottom - client_rect.top;
    
    return result;
}

void resize_dib_section(win32_offscreen_buffer* buffer, int width, int height) {
    if (buffer->memory) {
        VirtualFree(buffer->memory, 0, MEM_RELEASE);
    }
    
    int bytes_per_pixel = 4;
    
    buffer->width = width;
    buffer->height = height;
    
    buffer->info.bmiHeader.biSize = sizeof(buffer->info.bmiHeader);
    buffer->info.bmiHeader.biWidth = buffer->width;
    buffer->info.bmiHeader.biHeight = -buffer->height;
    buffer->info.bmiHeader.biPlanes = 1;
    buffer->info.bmiHeader.biBitCount = 32;
    buffer->info.bmiHeader.biCompression = BI_RGB;
    
    int bitmap_memory_size = (buffer->width * buffer->height) * bytes_per_pixel;
    buffer->memory = VirtualAlloc(0, bitmap_memory_size, MEM_COMMIT, PAGE_READWRITE);
    
    buffer->pitch = buffer->width * bytes_per_pixel;
    buffer->bytes_per_pixel = bytes_per_pixel;
}

void display_buffer_in_window(HDC device_context, window_dimension dimension) {
    StretchDIBits(device_context,
                  0, 0, dimension.width, dimension.height,
                  0, 0, global_buffer.width, global_buffer.height,
                  global_buffer.memory,
                  &global_buffer.info,
                  DIB_RGB_COLORS, SRCCOPY);
}

void free_file_memory(void *memory) {
    if (memory) {
        VirtualFree(memory, 0, MEM_RELEASE);
    }
}

read_file_result read_entire_file(LPCSTR filename) {
    read_file_result result = {};
    
    HANDLE file_handle = CreateFileA(filename, GENERIC_READ, FILE_SHARE_READ, 0, OPEN_EXISTING, 0, 0);
    
    if (file_handle != INVALID_HANDLE_VALUE) {
        LARGE_INTEGER file_size;
        if(GetFileSizeEx(file_handle, &file_size)) {
            unsigned int file_size32 = file_size.QuadPart;
            result.contents = VirtualAlloc(0, file_size32, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE);
            
            if (result.contents) {
                DWORD bytes_read;
                if (ReadFile(file_handle, result.contents, file_size32, &bytes_read, 0) && (file_size32 == bytes_read)) {
                    // File read successfully.
                    result.contents_size = file_size32;
                } else {
                    // TODO: Logging
                    free_file_memory(result.contents);
                    result.contents = 0;
                }
            } else {
                // TODO: Logging
            }
        } else {
            // TODO: Logging
        }
        
        CloseHandle(file_handle);
    } else {
        // TODO: Logging
    }
    
    return result;
}

bitmap_result debug_load_bitmap(char* filename) {
    bitmap_result bmp_result = {};

    read_file_result file_result = read_entire_file(filename);
    unsigned char *contents = (unsigned char *)file_result.contents;

    bmp_result.file_header = (BITMAPFILEHEADER *)contents;
    bmp_result.info_header = (BITMAPINFOHEADER *)(contents + 14);
    bmp_result.pixels = (unsigned int *)(contents + bmp_result.file_header->bfOffBits);
    bmp_result.stride = ((((bmp_result.info_header->biWidth * bmp_result.info_header->biBitCount) + 31) & ~31) >> 3);

    return bmp_result;
}

void render_bmp(int x_pos, int y_pos, win32_offscreen_buffer *buffer, bitmap_result bmp) {
    int width = bmp.info_header->biWidth;
    int height = bmp.info_header->biHeight;

    unsigned char* dest_row = (unsigned char*)buffer->memory + (y_pos * buffer->pitch + x_pos);

    // NOTE: Doing this calculation on the source row because the bitmaps are bottom up,
    // whereas the window is top-down. So must start at the bottom of the source bitmap,
    // working left to right.
    unsigned char* source_row = (unsigned char*)(bmp.pixels + ((bmp.stride / 4) * (height - 1)));

    for (int y = y_pos; y < y_pos + height; y++) {
        unsigned int* dest = (unsigned int*)dest_row;
        unsigned int* source = (unsigned int*)source_row;

        for (int x = x_pos; x < x_pos + width; x++) {
            *dest = *source;
            dest++;
            source++;
        }

        dest_row += buffer->pitch;
        source_row -= bmp.stride;
    }
}

LRESULT CALLBACK window_proc(HWND window, UINT message, WPARAM w_param, LPARAM l_param) {
    LRESULT result = 0;

    switch (message) {
        break;
        case WM_SIZE: {
            window_dimension dim = get_window_dimension(window);
            resize_dib_section(&global_buffer, dim.width, dim.height);
        }
        break;

        case WM_CLOSE: {
            OutputDebugStringA("WM_CLOSE\n");
            should_quit = 1;
        }
        break;

        case WM_ACTIVATEAPP: {
            OutputDebugStringA("WM_ACTIVATEAPP\n");
        }
        break;

        case WM_DESTROY: {
            OutputDebugStringA("WM_DESTROY\n");
        }
        break;

        case WM_PAINT: {
            PAINTSTRUCT paint;
            HDC device_context = BeginPaint(window, &paint);
            
            window_dimension dimension = get_window_dimension(window);
            display_buffer_in_window(device_context, dimension);
            
            OutputDebugStringA("WM_PAINT\n");

            EndPaint(window, &paint);
        }
        break;

        default: {
            result = DefWindowProc(window, message, w_param, l_param);
        }
        break;
    }

    return result;
}

int CALLBACK WinMain(HINSTANCE instance, HINSTANCE prev_instance, LPSTR command_line, int show_code) {
    WNDCLASS window_class = {};

    window_class.style = CS_HREDRAW | CS_VREDRAW | CS_OWNDC;
    window_class.lpfnWndProc = window_proc;
    window_class.hInstance = instance;
    window_class.lpszClassName = "PokerWindowClass";
    
    if (RegisterClassA(&window_class)) {
        HWND window_handle = CreateWindowExA(0, window_class.lpszClassName, "Poker",
                                      WS_OVERLAPPEDWINDOW | WS_VISIBLE, CW_USEDEFAULT, CW_USEDEFAULT,
                                      CW_USEDEFAULT, CW_USEDEFAULT, 0, 0, instance, 0);

        if (window_handle) {
            HDC device_context = GetDC(window_handle);
            
            window_dimension dim = get_window_dimension(window_handle);
            resize_dib_section(&global_buffer, dim.width, dim.height);
            
            char *filename = "c:/stuff/Sierpinski.bmp";
            bitmap_result img = debug_load_bitmap(filename);
            
            // MESSAGE LOOP
            while (!should_quit) {
                MSG msg;
                
                while (PeekMessage(&msg, 0, 0, 0, PM_REMOVE)) {
                    if (msg.message == WM_QUIT) {
                        should_quit = 1;
                    }
                    
                    TranslateMessage(&msg);
                    DispatchMessageA(&msg);
                }
                
                render_bmp(0, 0, &global_buffer, img);
                
                window_dimension dimension = get_window_dimension(window_handle);
                display_buffer_in_window(device_context, dimension);
            }
        } else {
            OutputDebugStringA("ERROR: Unable to create window.");
        }
    } else {
        OutputDebugStringA("ERROR: Unable to register the window class.");
    }
}
请注意,源位图的 biBitCount 为 24,而屏幕外缓冲区位图的 biBitCount 为 32。

最佳答案

对于绘制位图,有更简单的方法。您不必自己解析 .bmp 文件。给两个 sample 如下你可以试一试。

第一种方法使用 LoadImage 功能 .引用 "How to draw image on a window?"

case WM_CREATE:
{
    hBitmap = (HBITMAP)LoadImage(hInst, L"C:\\projects\\native_poker\\card-BMPs\\c08.bmp", IMAGE_BITMAP, 0, 0, LR_LOADFROMFILE);
}
break;
case WM_PAINT:
{
    PAINTSTRUCT     ps;
    HDC             hdc;
    BITMAP          bitmap;
    HDC             hdcMem;
    HGDIOBJ         oldBitmap;

    hdc = BeginPaint(hWnd, &ps);

    hdcMem = CreateCompatibleDC(hdc);
    oldBitmap = SelectObject(hdcMem, hBitmap);

    GetObject(hBitmap, sizeof(bitmap), &bitmap);
    BitBlt(hdc, 0, 0, bitmap.bmWidth, bitmap.bmHeight, hdcMem, 0, 0, SRCCOPY);

    SelectObject(hdcMem, oldBitmap);
    DeleteDC(hdcMem);

    EndPaint(hWnd, &ps);
}
break;

第二种方法使用 GDI+。 引用 "Loading and Displaying Bitmaps" .
#include <windows.h>
#include <objidl.h>
#include <gdiplus.h>
using namespace Gdiplus;
#pragma comment (lib,"Gdiplus.lib")

//...

VOID OnPaint(HDC hdc)
{
    Graphics graphics(hdc);
    Image *image = Image::FromFile(L"C:\\projects\\native_poker\\card-BMPs\\c08.bmp");
    graphics.DrawImage(image, 10, 10);
}

LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam)
{
    case WM_PAINT:
    {
        PAINTSTRUCT ps;
        HDC hdc = BeginPaint(hWnd, &ps);
        OnPaint(hdc);
        EndPaint(hWnd, &ps);
    }
    break;

//...

}

关于c++ - 使用 winapi 加载/渲染位图问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62178508/

相关文章:

c++ - PugiXML C++ 获取元素(或标签)的内容

c++ - 在 CUDA 中共享内存? CODE 是如何工作的?

c++ - 在 C++ 中检测一个或两个的补码架构?

Android 位图解码和缩放质量损失

android - Android 上的 NV21 转位图,图像非常暗、灰度还是黄色?

android - ClassCastException : android. 图形.Bitmap & ArrayList<>

c++ - 尝试在 OS X 10.6 上安装 libxml++

windows - "An unhandled non-continuable exception was thrown during process load"

c - 如何从 pid 中杀死(和关闭)标签?

c - 通过断点续传上传请求的 google Drive 失败,返回错误代码 12156。如果有人知道这一点,请回复?