7,655
社区成员
发帖
与我相关
我的任务
分享
/*
* 下载并转换图像为标准位图格式
* 成功返回宽(低字节),高(高字节),失败返回0
*/
LONG ConvertImage(LPCTSTR lpstrImgUrl,HBITMAP *hBitmap)
{
CHttpRequest httpRequ;
if(!InitHttpRequest(&httpRequ))return FALSE;
//下载图片
if(!httpRequ.OpenConnect(lpstrImgUrl,CHttpRequest::RequestType::GET))return FALSE;
if(!httpRequ.SendRequest())return FALSE;
DWORD dwLen=0;
BYTE *byData=NULL;
if(!httpRequ.ReadData(NULL,&dwLen))return FALSE;
byData=new BYTE[dwLen];
if(!httpRequ.ReadData(byData,&dwLen)) goto End;
///解码图像
LONG lRetn=0;
IImage *pImage=NULL;
IImagingFactory *pImagingFactory=NULL;
HRESULT hrCoInit;
HDC hdcCont=NULL,hdcMem=NULL;
if (FAILED(hrCoInit=CoInitializeEx(NULL, COINIT_MULTITHREADED)))goto End;
if(FAILED(CoCreateInstance(CLSID_ImagingFactory,NULL,CLSCTX_INPROC_SERVER,IID_IImagingFactory,(void**) &pImagingFactory)))goto End;
if(FAILED(pImagingFactory->CreateImageFromBuffer(byData,dwLen,BufferDisposalFlag::BufferDisposalFlagCoTaskMemFree,&pImage)))goto End;
ImageInfo imgInfo;
if(FAILED(pImage->GetImageInfo(&imgInfo)))goto End;
//将解码后的图像画入内存DC中
hdcCont=GetDC(NULL);
*hBitmap=CreateCompatibleBitmap(hdcCont,imgInfo.Width,imgInfo.Height);
hdcMem=CreateCompatibleDC(hdcCont);
SelectObject(hdcMem,*hBitmap);
RECT rect={0,0,imgInfo.Width,imgInfo.Height};
pImage->Draw(hdcMem,&rect,NULL);
//返回位置的宽,高
lRetn=MAKELONG(imgInfo.Width,imgInfo.Height);
End:
if(hdcMem)DeleteDC(hdcMem);
if(hdcCont)DeleteDC(hdcCont);
if(pImage)pImage->Release();
if(pImagingFactory)pImagingFactory->Release();
if(byData)delete[] byData;
if(SUCCEEDED(hrCoInit))CoUninitialize();
return lRetn;
}