mfc 通过http地址下载图片
时间: 2023-10-07 11:09:01 浏览: 39
要在 MFC 中通过 HTTP 地址下载图片,可以使用 CInternetSession 和 CHttpFile 类。以下是一个简单的示例代码:
```cpp
CString strURL = _T("http://www.example.com/image.jpg");
CInternetSession session;
CHttpFile* pFile = NULL;
try {
pFile = (CHttpFile*) session.OpenURL(strURL);
if (pFile) {
// 获取图片内容并保存到文件
CString strFilePath = _T("C:\\image.jpg");
CFile file(strFilePath, CFile::modeCreate | CFile::modeWrite);
BYTE buffer[1024];
UINT nRead = 0;
while ((nRead = pFile->Read(buffer, 1024)) > 0) {
file.Write(buffer, nRead);
}
file.Close();
}
}
catch (CInternetException* e) {
// 处理异常
e->Delete();
}
if (pFile) {
pFile->Close();
delete pFile;
}
session.Close();
```
该代码使用 `OpenURL` 方法打开 HTTP 地址,返回一个 `CHttpFile` 对象,然后使用 `Read` 方法读取图片内容并保存到本地文件。你需要替换代码中的 URL 和文件路径为你实际使用的值。