项目中需要用到的功能。
void Screenshot()
{
CDC *pDC;
pDC = CDC::FromHandle(GetDC(GetDesktopWindow()));
if(pDC == NULL)
return;
int BitPerPixel = pDC->GetDeviceCaps(BITSPIXEL);
int Width = pDC->GetDeviceCaps(HORZRES);
int Height = pDC->GetDeviceCaps(VERTRES); CDC memDC;
if(memDC.CreateCompatibleDC(pDC) == )
return; CBitmap memBitmap, *oldmemBitmap;
if(memBitmap.CreateCompatibleBitmap(pDC, Width, Height) == NULL)
return; oldmemBitmap = memDC.SelectObject(&memBitmap);
if(oldmemBitmap == NULL)
return;
if(memDC.BitBlt(, , Width, Height, pDC, , , SRCCOPY) == )
return; CPoint po;
GetCursorPos(&po);
HICON hinco = (HICON)GetCursor();
memDC.DrawIcon(po.x- , po.y - , hinco); BITMAP bmp;
memBitmap.GetBitmap(&bmp); BITMAPINFOHEADER bih = {};
bih.biBitCount = bmp.bmBitsPixel;
bih.biCompression = BI_RGB;
bih.biHeight = bmp.bmHeight;
bih.biPlanes = ;
bih.biSize = sizeof(BITMAPINFOHEADER);
bih.biSizeImage = bmp.bmWidthBytes * bmp.bmHeight;
bih.biWidth = bmp.bmWidth; BITMAPFILEHEADER bfh = {};
bfh.bfOffBits = sizeof(BITMAPFILEHEADER) + sizeof(BITMAPINFOHEADER);
bfh.bfSize = bfh.bfOffBits + bmp.bmWidthBytes * bmp.bmHeight;
bfh.bfType = (WORD)0x4d42; BYTE* pImgBuff = new BYTE[bmp.bmWidthBytes * bmp.bmHeight]; GetDIBits(memDC.m_hDC, (HBITMAP) memBitmap.m_hObject
, , Height, pImgBuff, (LPBITMAPINFO) &bih, DIB_RGB_COLORS);
memDC.SelectObject(oldmemBitmap); BYTE* pJpg = NULL;
int nJpgSize = BmpToJpeg(pImgBuff, bmp.bmWidth, bmp.bmHeight, &pJpg); if (NULL != pJpg)
{
delete[] pJpg;
} delete [] pImgBuff;
}
附上 BmpToJpeg
int BmpToJpeg(BYTE *pSrc, int nWidth, int nHeight, BYTE** ppDes)
{
struct jpeg_compress_struct cinfo;
struct jpeg_error_mgr jerr;
JSAMPROW row_pointer[];
int row_stride;
cinfo.err = jpeg_std_error(&jerr);
jpeg_create_compress(&cinfo); DWORD dwLen = nWidth * nHeight * ;
jpeg_mem_dest(&cinfo, ppDes, &dwLen); cinfo.image_width = nWidth;
cinfo.image_height = nHeight;
cinfo.input_components = ;
cinfo.in_color_space = JCS_RGB; jpeg_set_defaults(&cinfo);
jpeg_set_quality(&cinfo, JPEG_QUALITY, TRUE);
jpeg_start_compress(&cinfo, TRUE); row_stride = nWidth * ;
for (int i=, j=; j < nWidth*nHeight*; i+=, j+=) //BGRA => RGB
{
*(pSrc+i)=*(pSrc+j+);
*(pSrc+i+)=*(pSrc+j+);
*(pSrc+i+)=*(pSrc+j);
} while (cinfo.next_scanline < cinfo.image_height)
{
row_pointer[] = &pSrc[(cinfo.image_height - cinfo.next_scanline - ) * row_stride];
(void) jpeg_write_scanlines(&cinfo, row_pointer, );
}
jpeg_finish_compress(&cinfo); jpeg_destroy_compress(&cinfo);
return dwLen;
}
需要用到的头文件
#define JPEG_QUALITY 50
extern "C"
{
#include "jpeglib.h"
#include "jmorecfg.h"
#include "jconfig.h"
}