windows gdi截图保存bmp

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了windows gdi截图保存bmp相关的知识,希望对你有一定的参考价值。

/*
 * windows gdi截屏保存bmp文件
 */
#include "stdio.h"
#include "windows.h"

void save_bgrdata_to_bmp(void *data, int size, int width, int height,char *bmpPath,int bpp)  
{  
	BITMAPFILEHEADER bmpheader;
	BITMAPINFOHEADER bmpinfo;
	FILE *fp = fopen(bmpPath,"wb+");

	bmpheader.bfType = 0x4d42;  
	bmpheader.bfReserved1 = 0;  
	bmpheader.bfReserved2 = 0;  
	bmpheader.bfOffBits = sizeof(BITMAPFILEHEADER) + sizeof(BITMAPINFOHEADER);  
	bmpheader.bfSize = bmpheader.bfOffBits + width*height*bpp/8;  

	bmpinfo.biSize = sizeof(BITMAPINFOHEADER);  
	bmpinfo.biWidth = width;  
	bmpinfo.biHeight = -height;  
	bmpinfo.biPlanes = 1;  
	bmpinfo.biBitCount = bpp;  
	bmpinfo.biCompression = BI_RGB;  
	bmpinfo.biSizeImage = (width*bpp+31)/32*4*height;  
	bmpinfo.biXPelsPerMeter = 100;  
	bmpinfo.biYPelsPerMeter = 100;  
	bmpinfo.biClrUsed = 0;  
	bmpinfo.biClrImportant = 0;  

	fwrite(&bmpheader, sizeof(bmpheader), 1, fp);  
	fwrite(&bmpinfo, sizeof(bmpinfo), 1, fp);  
	fwrite(data, size, 1, fp);  

	fclose(fp);  
}  

int main(int argc,char *argv)
{
	HWND dtHwnd = GetDesktopWindow();
	HDC dtHdc = GetDC(dtHwnd);

	int dtWidth = GetSystemMetrics(SM_CXSCREEN);
	int dtHeight = GetSystemMetrics(SM_CYSCREEN);

	HDC dtHdcBuf = CreateCompatibleDC(NULL);
	HBITMAP hBitmap = CreateCompatibleBitmap(dtHdc,dtWidth,dtHeight);
	SelectObject(dtHdcBuf, hBitmap);
	BitBlt(dtHdcBuf, 0, 0, dtWidth, dtHeight, dtHdc, 0, 0, SRCCOPY);

	int bitSize = dtWidth*dtHeight*4;
	BYTE *bit = new BYTE[bitSize];
	LONG re = GetBitmapBits(hBitmap, bitSize, bit);
	if(bit && re)
	{
		save_bgrdata_to_bmp(bit, bitSize, dtWidth, dtHeight,"gdi.bmp",32);
		free(bit);
	}

	DeleteObject(hBitmap);
	DeleteDC(dtHdcBuf);

	ReleaseDC(dtHwnd,dtHdc);
	return 1;
}

gdi_bmp.cpp

以上是关于windows gdi截图保存bmp的主要内容,如果未能解决你的问题,请参考以下文章

如何在 SDL 2 中获取并保存 BMP 屏幕截图?

C# 控制台应用程序 - 如何使用 GDI+ 在 BMP/JPG 文件中绘图?

用VC++ 怎样把图像输出保存成jepg或bmp图像

将特定窗口的屏幕截图保存为窗口中的 bmp

Gdi+ 多台显示器截图

用vs2010编写C#程序,将图片保存到一个文件夹中,下次循环覆盖保存,提示gdi+中发生一般性错误。。。