c-使用BitBlt无法正确显示图像



所以我昨天刚开始用c。为了尽可能地保持新鲜感,我尝试了一个相当简单的任务,在桌面上显示一张图像。首先我尝试了像素:

#include <stdio.h>
#include <stdlib.h>
#include <windows.h>
int main() {

int a;
int b;
int x = 0;
COLORREF clr =  RGB(200,100,30);
HDC dc = GetDC(NULL);
while (x != 1){
for (a=0; a<20; a++){
for (b=0; b<20; b++){
SetPixel(dc,b,a, clr);
}
}
}
return 0;
}

它奏效了。现在我尝试对整个图像进行处理,但失败了:

#include <stdio.h>
#include <stdlib.h>
#include <windows.h>
int main() {

int x = 0;
HBITMAP hBitmap = (HBITMAP)LoadImage(NULL, "neco.bmp", IMAGE_BITMAP, 487, 456, LR_LOADFROMFILE); 
HDC dc = GetDC(NULL);

while (x != 1){
BitBlt(dc,0,0,487,456,hBitmap,0,0,SRCPAINT);
}
return 0;
}

我假设它读取图像,就好像我使用BLACKNESS作为BitBlt的最后一个参数一样——它确实显示了给定尺寸的黑色矩形。但通常情况下,不会发生其他情况。此外,脚本编译时不会引发任何错误。

BitBlt(dc,0,0,487,456,Bitmap,0,0,SRCPAINT);

在这一行中,您已尝试将位图句柄传递给

设备上下文句柄注意,BitBlt将比特从一个设备上下文传输到另一个设备。您可以为位图创建另一个设备上下文,在其中选择位图,然后执行您想要的操作。例如:

#include <windows.h>
int APIENTRY WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance,
LPSTR lpCmdLine, int nCmdShow)
{
HBITMAP hBitmap = (HBITMAP)LoadImage(NULL, "neco.bmp", IMAGE_BITMAP,
487, 456, LR_LOADFROMFILE);
HDC hDC = GetDC(NULL);
HDC hBitmapDC = CreateCompatibleDC(hDC);
HBITMAP hOldBitmap = (HBITMAP)SelectObject(hBitmapDC, hBitmap);
BitBlt(hDC, 0, 0, 487, 456, hBitmapDC, 0, 0, SRCCOPY);
/* Don't forget to release resources that you've acquired */
SelectObject(hBitmapDC, hOldBitmap)
DeleteObject(hBitmap);
DeleteDC(hBitmapDC);
ReleaseDC(HWND_DESKTOP, hDC);
return 0;
}

编辑:感谢@IInspectable更正我关于GDI资源释放的问题。

最新更新