標籤:set point har stdio.h screen nts window cpp compress
/** windows gdi截屏使用libjpeg儲存jpg檔案*/#include "stdio.h"#include "windows.h"#include "libjpeg/jpeglib.h"#pragma comment(lib,"libjpeg/libjpeg.lib")void bgr_to_jpgfile(BYTE *rgb,int size,int w,int h,char *jpgfile){struct jpeg_error_mgr jerr;jpeg_std_error(&jerr);struct jpeg_compress_struct cinfo;cinfo.err = &jerr;jpeg_create_compress(&cinfo);FILE *fp = fopen(jpgfile,"wb+");jpeg_stdio_dest(&cinfo,fp);cinfo.image_width = w;cinfo.image_height = h;cinfo.input_components = 3;cinfo.in_color_space = JCS_RGB;jpeg_set_defaults(&cinfo);jpeg_set_quality(&cinfo, 100, TRUE);jpeg_start_compress(&cinfo,TRUE);int row_stride = cinfo.image_width*cinfo.input_components;JSAMPROW row_pointer[1];while(cinfo.next_scanline < cinfo.image_height){row_pointer[0] = & rgb[cinfo.next_scanline * row_stride];//row_pointer[0] = & rgb[(cinfo.image_height-cinfo.next_scanline-1)*row_stride];(void)jpeg_write_scanlines(&cinfo, row_pointer, 1);}jpeg_finish_compress(&cinfo);jpeg_destroy_compress(&cinfo);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){BYTE *buf = bit; for(int i=0, j=0; j < bitSize; i+=3, j+=4) { *(buf+i) = *(buf+j); *(buf+i+1) = *(buf+j+1); *(buf+i+2) = *(buf+j+2); } bgr_to_jpgfile(bit,dtWidth*dtHeight*3,dtWidth, dtHeight,"gdi_libjpeg.jpg");free(bit);}DeleteObject(hBitmap);DeleteDC(dtHdcBuf);ReleaseDC(dtHwnd,dtHdc);return 1;}
gdi_jpg.cpp
windows gdi截屏使用libjpeg儲存jpg檔案