windows gdi截屏使用libjpeg保存jpg文件

Posted

tags:

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

/*
* 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文件的主要内容,如果未能解决你的问题,请参考以下文章

C# wpf 使用GDI+实现截屏

windows directx9截屏保存bmp文件

解决使用 libjpeg 保存图片时因磁盘写入失败导致程序退出的问题

gdi 对象保存在哪里?

windows打印GDI+出现锯齿和虚化问题的解决方法

windows打印GDI+出现锯齿和虚化问题的解决方法