实现函数如下, 测试有效
#include <afxwin.h>
#include <gdiplus.h>
#pragma comment(lib, "gdiplus.lib")
using namespace Gdiplus;
// 获取 JPEG 编码器的 CLSID
int GetEncoderClsid(const WCHAR* format, CLSID* pClsid) {
UINT num = 0; // number of image encoders
UINT size = 0; // size of the image encoder array in bytes
Gdiplus::GetImageEncodersSize(&num, &size);
if (size == 0)
return -1; // Failure
Gdiplus::ImageCodecInfo* pImageCodecInfo = (Gdiplus::ImageCodecInfo*)(malloc(size));
if (pImageCodecInfo == NULL)
return -1; // Failure
Gdiplus::GetImageEncoders(num, size, pImageCodecInfo);
for (UINT j = 0; j < num; ++j) {
if (wcscmp(pImageCodecInfo[j].MimeType, format) == 0) {
*pClsid = pImageCodecInfo[j].Clsid;
free(pImageCodecInfo);
return j; // Success
}
}
free(pImageCodecInfo);
return -1; // Failure
}
void SaveControlAsJPEG2(HWND hWnd, const CString& filename) {
// 获取控件的客户区大小
CRect rect;
::GetClientRect(hWnd, &rect);
int width = rect.Width();
int height = rect.Height();
// 创建一个兼容的内存DC
CDC memDC;
memDC.CreateCompatibleDC(NULL);
// 设置内存DC的背景色为白色
// memDC.FillSolidRect(0, 0, width, height, RGB(255, 255, 255));
// 创建一个内存位图
CBitmap bmp;
bmp.CreateCompatibleBitmap(&memDC, width, height);
memDC.SelectObject(&bmp);
// 在内存DC中绘制控件内容
::SendMessage(hWnd, WM_PRINTCLIENT, (WPARAM)memDC.GetSafeHdc(), PRF_CLIENT);
// 初始化 GDI+
Gdiplus::GdiplusStartupInput gdiplusStartupInput;
ULONG_PTR gdiplusToken;
Gdiplus::GdiplusStartup(&gdiplusToken, &gdiplusStartupInput, NULL);
// 创建 GDI+ Bitmap 对象
Gdiplus::Bitmap bitmap(bmp, NULL);
// Gdiplus::Bitmap bitmap(width, height, PixelFormat24bppRGB);
Gdiplus::Graphics graphics(&bitmap);
Gdiplus::Rect destRect(0, 0, width, height);
graphics.DrawImage(&bitmap, destRect, 0, 0, width, height, Gdiplus::UnitPixel);
// 保存为 JPEG 文件
CLSID clsid;
GetEncoderClsid(L"image/jpeg", &clsid);
bitmap.Save(filename, &clsid, NULL);
// 清理资源
// Gdiplus::GdiplusShutdown(gdiplusToken);
}
// 测试
void OnBnClickedButton1()
{
// TODO: 在此添加控件通知处理程序代码
SaveControlAsJPEG2(GetDlgItem(IDC_BUTTON2)->GetSafeHwnd(), L"D://IDC_BUTTON2.jpg"); // 成功
SaveControlAsJPEG2(GetDlgItem(IDC_STATIC_TITLE)->GetSafeHwnd(), L"D://IDC_STATIC_TITLE.jpg"); //成功
}