VC++ GDI+将CDC保存为图片文件(bmp、jpg、png)

int GetEncoderClsid(const wchar_t* format, CLSID* pClsid)
{
	UINT  num = 0;
	UINT  size = 0;
	ImageCodecInfo* pImageCodecInfo = NULL;
	GetImageEncodersSize(&num, &size);
	if (size == 0)
		return -1;

	pImageCodecInfo = (ImageCodecInfo*)(malloc(size));
	if (pImageCodecInfo == NULL)
		return -1;

	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;
		}
	}
	free(pImageCodecInfo);
	return -1;
}

BOOL SaveAs(CDC* pDC, const wchar_t* lpszFilename)
{
	CBitmap* pBitmap = pDC->GetCurrentBitmap();
	BITMAP bmp;
	pBitmap->GetBitmap(&bmp);
	CRect rcClient = CRect(0, 0, bmp.bmWidth, bmp.bmHeight);
	CBitmap screenbitmap;
	screenbitmap.CreateCompatibleBitmap(pDC, rcClient.Width(), rcClient.Height());
	CDC memDC;
	memDC.CreateCompatibleDC(pDC);
	CBitmap *pOldBitmap = memDC.SelectObject(&screenbitmap);
	memDC.SetStretchBltMode(HALFTONE);
	memDC.StretchBlt(0, 0, rcClient.Width(), rcClient.Height(), pDC, 0, 0, rcClient.Width(), rcClient.Height(), SRCCOPY);
	memDC.SelectObject(pOldBitmap);
	Bitmap bitmap((HBITMAP)screenbitmap.GetSafeHandle(), NULL);

	CLSID picClsid;
	CString sFileName = lpszFilename;
	CString sExt = sFileName.Right(3).MakeLower();
	if (sExt == "jpg")
	{
		ULONG encoderQuality = 80; //压缩比例
		EncoderParameters   encoderParameters;
		encoderParameters.Count = 1;
		encoderParameters.Parameter[0].Guid = EncoderQuality;
		encoderParameters.Parameter[0].Type = EncoderParameterValueTypeLong;
		encoderParameters.Parameter[0].NumberOfValues = 1;
		encoderParameters.Parameter[0].Value = &encoderQuality;
		GetEncoderClsid(L"image/jpeg", &picClsid);
		bitmap.Save(lpszFilename, &picClsid, &encoderParameters);
	}
	else if (sExt == "png")
	{
		GetEncoderClsid(L"image/png", &picClsid);
		bitmap.Save(lpszFilename, &picClsid, NULL);
	}
	else if (sExt == "bmp")
	{
		GetEncoderClsid(L"image/bmp", &picClsid);
		bitmap.Save(lpszFilename, &picClsid, NULL);
	}
	else
	{
		DeleteObject(screenbitmap);
		memDC.DeleteDC();
		return FALSE;
	}

	DeleteObject(screenbitmap);
	memDC.DeleteDC();
	return TRUE;
}

 

  • 1
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值