本人采用VS2003开发平台,由于可以兼容VC6.0的大量代码。但是要实现目前C#的大量功能,还是要费不少功夫的。下面讲下如何如下图片下载,然后显示在图片控件的功能。单独封装了两个函数可以只直接使用。
下载远程图片函数如下:
CString dir_name="";
dir_name=ReturnPath();
HRESULT hre = URLDownloadToFile(0, _T("http://172.28.125.74/auction/uploads/images/2014-03/1395916979-126367078.jpg"), _T(dir_name + "/1.jpg"), 0, NULL);
if(SUCCEEDED(hre)){
Sleep(1000);
CDC *pDC = m_edit.GetDC();
ShowJpgGif(pDC, _T(dir_name + "/1.jpg"), 0, 0,(1024 / 2)-20, (768 / 2)-60);
}
本地路径获取代码:
CString CAuctionShadowDlg::ReturnPath()
{
CString sPath;
GetModuleFileName(NULL, sPath.GetBufferSetLength(MAX_PATH + 1), MAX_PATH);
sPath.ReleaseBuffer();
int nPos;
nPos = sPath.ReverseFind('\\');
sPath = sPath.Left(nPos);
return sPath;
}
图片显示到控件代码:
/**
CDC *pDC, 传入控件
CString strPath, 图片本地路径
int x, 控件摆放图片的起点坐标位置
int y,
int widthX,控件摆放图片的宽和高
int heigthY
*/
bool CAuctionShadowDlg::ShowJpgGif(CDC *pDC, CString strPath, int x, int y,int widthX,int heigthY)
{
IStream *pStm;
CFileStatus fstatus;
CFile file;
LONG cb;
if (file.Open(strPath,CFile::modeRead)&&file.GetStatus(strPath,fstatus)&&((cb = fstatus.m_size) != -1))
{
HGLOBAL hGlobal = GlobalAlloc(GMEM_MOVEABLE, cb);
LPVOID pvData = NULL;
if (hGlobal != NULL)
{
pvData = GlobalLock(hGlobal);
if (pvData != NULL)
{
file.Read(pvData, cb);
GlobalUnlock(hGlobal);
CreateStreamOnHGlobal(hGlobal, TRUE, &pStm);
}
}
}
else
return false;
//显示JPEG和GIF格式的图片,GIF只能显示一帧,还不能显示动画,
//要显示动画GIF请使用ACTIVE控//件。
IPicture *pPic;
//load image from file stream
if(SUCCEEDED(OleLoadPicture(pStm,fstatus.m_size,TRUE,IID_IPicture,(LPVOID*)&pPic)))
{
OLE_XSIZE_HIMETRIC hmWidth;
OLE_YSIZE_HIMETRIC hmHeight;
pPic->get_Width(&hmWidth);
pPic->get_Height(&hmHeight);
double fX,fY;
//get image height and width
fX = (double)pDC->GetDeviceCaps(HORZRES)*(double)hmWidth/((double)pDC->GetDeviceCaps(HORZSIZE)*100.0);
fY = (double)pDC->GetDeviceCaps(VERTRES)*(double)hmHeight/((double)pDC->GetDeviceCaps(VERTSIZE)*100.0);
//use render function display image
if(widthX>0&&fX>widthX){
if(FAILED(pPic->Render(*pDC,x,y,widthX,heigthY,0,hmHeight,hmWidth,-hmHeight,NULL)))
{
pPic->Release();
return false;
}
}else{
if(FAILED(pPic->Render(*pDC,x,y,(DWORD)fX,(DWORD)fY,0,hmHeight,hmWidth,-hmHeight,NULL)))
{
pPic->Release();
return false;
}
}
pPic->Release();
}
else
return false;
return true;
}