抓取屏幕代码
char* getScreen(unsigned long &jpg_size){ HWND DeskWnd=::GetDesktopWindow();//获取桌面窗口句柄RECT DeskRC;::GetClientRect(DeskWnd,&DeskRC);//获取窗口大小HDC DeskDC=GetDC(DeskWnd);//获取窗口DCHBITMAP DeskBmp=::CreateCompatibleBitmap(DeskDC,DeskRC.right,DeskRC.bottom);//兼容位图HDC memDC=::CreateCompatibleDC(DeskDC);//兼容DCSelectObject(memDC,DeskBmp);//把兼容位图选入兼容DC中BitBlt(memDC,0,0,DeskRC.right,DeskRC.bottom,DeskDC,0,0,SRCCOPY);BITMAP bmInfo;DWORD bmDataSize;char *bmData;//位图数据GetObject(DeskBmp,sizeof(BITMAP),&bmInfo);//根据位图句柄,获取位图信息bmDataSize=bmInfo.bmWidthBytes*bmInfo.bmHeight;//计算位图数据大小bmData=new char[bmDataSize];//分配数据BITMAPFILEHEADER bfh;//位图文件头bfh.bfType=0x4d42;bfh.bfSize=bmDataSize+54;bfh.bfReserved1=0;bfh.bfReserved2=0;bfh.bfOffBits=54;BITMAPINFOHEADER bih;//位图信息头bih.biSize=40;bih.biWidth=bmInfo.bmWidth;bih.biHeight=bmInfo.bmHeight;bih.biPlanes=1;bih.biBitCount=24;bih.biCompression=BI_RGB;bih.biSizeImage=bmDataSize;bih.biXPelsPerMeter=0;bih.biYPelsPerMeter=0;bih.biClrUsed=0;bih.biClrImportant=0;::GetDIBits(DeskDC,DeskBmp,0,bmInfo.bmHeight,bmData,(BITMAPINFO *)&bih,DIB_RGB_COLORS);//获取位图数据部分ReleaseDC(DeskWnd,DeskDC);DeleteDC(memDC);DeleteObject(DeskBmp);int sumSize = sizeof(BITMAPFILEHEADER)+sizeof(BITMAPINFOHEADER)+bmDataSize;char * stream = new char[sumSize];memcpy(stream,&bfh,sizeof(BITMAPFILEHEADER));memcpy(stream+sizeof(BITMAPFILEHEADER),&bih,sizeof(BITMAPINFOHEADER));memcpy(stream+sizeof(BITMAPFILEHEADER)+sizeof(BITMAPINFOHEADER),bmData,bmDataSize);delete bmData;bmData=NULL;/*HANDLE hFile=CreateFile(_T("d:\\Screen.bmp"),GENERIC_WRITE,0,NULL,CREATE_ALWAYS,FILE_ATTRIBUTE_NORMAL,0);//创建文件DWORD dwSize;WriteFile(hFile,(void *)stream,sumSize,&dwSize,0);//写入位图文件头::CloseHandle(hFile);//关闭文件句柄*/;char*p1=rgb_to_jpeg(reinterpret_cast<unsigned char*>(stream),jpg_size,bih.biWidth,bih.biHeight);delete stream;stream=NULL;return p1;}
对应编译好的jpeg.lib库文件下载地址
转为jpg图片代码
char * rgb_to_jpeg(unsigned char *rgb,unsigned long &jpg_size,int biWidth,int bmHeight)
{ struct jpeg_compress_struct jcs;struct jpeg_error_mgr jem;JSAMPROW row_pointer[1];int row_stride=0;unsigned char *jpg_buf=NULL;jcs.err = jpeg_std_error(&jem);jpeg_create_compress(&jcs);//printf("jpeg_mem_dest\n");jpeg_mem_dest(&jcs,&jpg_buf,&jpg_size);jcs.image_width =biWidth; jcs.image_height =bmHeight;jcs.input_components = 3;//1; jcs.in_color_space = JCS_RGB;//JCS_GRAYSCALE; jpeg_set_defaults(&jcs); jpeg_set_quality(&jcs,30,TRUE);jpeg_start_compress(&jcs, TRUE);row_stride =jcs.image_width * 3;while(jcs.next_scanline < jcs.image_height){//对每一行进行压缩 row_pointer[0] = &rgb[(jcs.image_height-jcs.next_scanline-1) * row_stride];(void)jpeg_write_scanlines(&jcs,row_pointer, 1);} jpeg_finish_compress(&jcs);jpeg_destroy_compress(&jcs);/*printf("jpg_size = %lu\n",jpg_size);FILE *p;p= fopen("d:\\04.jpg","wb");if(p==NULL)printf("error in fopen\n");fwrite(jpg_buf,1,jpg_size,p);fclose(p);*/return reinterpret_cast<char*>(jpg_buf);
}
可以关注以下公众号交流: