gdiplus 从内存加载绘制图片

参考:How to use GDI+ library to decode a jpeg in memory?

需求:通过http请求从nginx下载jpg图片,在本地窗口用gdiplus显示

通过http直接访问图片url,返回的jpg图片以字符串形式存在string对象中,可以先写为本地文件,再用gdiplus的FromFile函数从文件加载图片,缺点不言而喻,多了磁盘读写,还要处理图片更新删除问题,code:

// http请求部分
string data; // http response body

// 保存到文件
std::ofstream ofs(m_img_path, std::ofstream::binary);
ofs.write(data.c_str(), data.size());
ofs.close();

// ui绘制部分,需要在OnPaint中调用
Gdiplus::Graphics gwnd(GetSafeHwnd());
CRect rc;
GetClientRect(&rc); // 计算当前客户区,使得重绘时图片随窗口缩放
Gdiplus::Bitmap * lpBmp = Gdiplus::Bitmap::FromFile(m_preview_img.c_str());
Gdiplus::Status status = gwnd.DrawImage(lpBmp, rc.left, rc.top, rc.Width(), rc.Height());
if (status != Gdiplus::Status::Ok)
{
    loginfo("图片显示失败");
}
delete lpBmp;

直接从内存加载图片(你永远可以相信stackoverflow)注意

// http请求部分
string m_preview_img // http response body

// 从string构建gdi+ image
IStream* stream = SHCreateMemStream((BYTE *)m_preview_img.data(), m_preview_img.size());
Gdiplus::Image *image = Gdiplus::Image::FromStream(stream);

// 计算绘制位置
Gdiplus::Graphics gwnd(GetSafeHwnd());
CRect rc;
GetClientRect(&rc);

// 绘制图片
Gdiplus::Status status = gwnd.DrawImage(image, rc.left, rc.top, rc.Width(), rc.Height());
if (status != Gdiplus::Status::Ok)
{
    loginfo("图片显示失败");
}

stream->Release();
delete image;
posted @ 2022-04-12 20:50  jixhua  阅读(670)  评论(0编辑  收藏  举报