C++根據圖片url下載圖片


 

需要使用到URLDownloadToFile()函數,該函數在頭文件<urlmon.h>中聲明。

URLDownloadToFile()函數的定義如下:

1 HRESULT URLDownloadToFile( 
2     LPUNKNOWN pCaller,
3     LPCTSTR szURL,
4     LPCTSTR szFileName,
5     DWORD dwReserved,
6     LPBINDSTATUSCALLBACK lpfnCB
7 );

Parameters(參數含義):


 

pCaller

Pointer to the controlling IUnknown interface of the calling Microsoft ActiveX component (if the caller is an ActiveX component).

Microsoft ActiveX控件的接口的指針,如果不是控件,則為NULL

szURL

Pointer to a string value containing the URL to be downloaded. Cannot be set to NULL

要下載的url地址,不能為空

szFileName

Pointer to a string value containing the name of the file to create for bits that come from the download.

下載后保存的文件名

dwReserved

Reserved. Must be set to 0.

保留字段,必須為0

lpfnCB

Pointer to the caller's IBindStatusCallback interface. URLDownloadToFile calls this interface's IBindStatusCallback::OnProgress method on a connection activity, including the arrival of data. IBindStatusCallback::OnDataAvailable is never called.

下載進度狀態回調

 

Return Value
Returns one of the following values.
S_OK : The download started successfully.
E_OUTOFMEMORY: The buffer length is invalid, or there is insufficient memory to complete the operation.
INET_E_DOWNLOAD_FAILURE:The specified resource or callback interface was invalid.
 
由於函數的參數使用的是LPWSTR,而我們常用的是string,所以用到了MultiByteToWideChar()函數將string轉為LPWSTR
 
代碼如下
 1 /*
 2 @author:CodingMengmeng
 3 @theme:C++根據圖片url下載圖片
 4 @time:2017-1-6 22:58:00
 5 @blog:http://www.cnblogs.com/codingmengmeng/
 6 */
 7 #include <tchar.h>
 8 #include <iostream>
 9 #include <urlmon.h>
10 /*
11 #pragma comment(lib,"urlmon.lib")作用:
12 連接靜態庫到項目中,效果等同於:
13 項目屬性——鏈接器——輸入——附加依賴項中加入這個lib
14 (頭文件<urlmon.h>中只是包含了數據結構和函數聲明,是編譯階段;
15 鏈接階段將從靜態庫中恢復這些函數和數據並把他們和應用程序中的其它模塊組合在一起生成可執行文件,
16 該過程稱為“靜態鏈接”)
17 */
18 #pragma comment(lib,"urlmon.lib")
19 using namespace std;
20 
21 int _tmain(int argc, char* argv[])
22 {
23     string url = "http://pic104.nipic.com/file/20160715/6171480_185807154956_2.jpg";
24     size_t len = url.length();//獲取字符串長度
25     int nmlen = MultiByteToWideChar(CP_ACP, 0, url.c_str(), len + 1, NULL, 0);//如果函數運行成功,並且cchWideChar為零,
26     //返回值是接收到待轉換字符串的緩沖區所需求的寬字符數大小。
27     wchar_t* buffer = new wchar_t[nmlen];
28     MultiByteToWideChar(CP_ACP, 0, url.c_str(), len + 1, buffer, nmlen);
29     HRESULT hr = URLDownloadToFile(NULL, buffer,_T("E:\\C++lianxi\\Blog\\urlDownload2File\\urlDownload2File\\sky.jpg"), 0, NULL);
30     if (hr == S_OK)
31     {
32         cout << "ok" << endl;
33     }
34     return 0;
35 }

 

運行結果

 

程序輸出ok,且在指定目錄中也保存了下載到的圖片。 

以上。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM