C++ 根据图片url 批量 下载图片

时间:2018-05-07 22:48:24   收藏:0   阅读:1243

最近需要用到根据图片URL批量下载到本地的操作。查找了相关资料,记录在这儿。

 

1.首先在CSV文件中提取出url

技术分享图片

 

    ifstream fin("C:\\Users\\lenovo\\Desktop\\query_result0503.csv"); //打开文件流操作  
    string line;

    int cnt = 0;
    while (getline(fin, line) && cnt < 20)  
    {
        istringstream sin(line); //将整行字符串line读入到字符串流istringstream中  
        vector<string> urls; 
        string url;
        while (getline(sin, url, ,)) //以逗号为分隔符  
        {
            urls.push_back(url); 
        }
        
        cnt++;
        size_t found =     urls[0].find_last_of("/\\");
        if (found == string::npos) continue;
        string imgname = urls[0].substr(found+1);
        cout << "处理后:" << urls[0] << "----" <<cnt<<"----" <<imgname << endl;
   }

 

2.根据URL将图片保存到本地。

需要用到 URLDownloadToFile函数 。

踩的坑主要是 这个函数需要用到宽字符参数。。如果参数类型不正确。。那么你甭想下载得到正确文件。。。

需要用到 MultiByteToWideChar函数来转换一下。。。。

 

HRESULT URLDownloadToFile(
             LPUNKNOWN            pCaller,
             LPCTSTR              szURL,
             LPCTSTR              szFileName,
  _Reserved_ DWORD                dwReserved,
             LPBINDSTATUSCALLBACK lpfnCB
);

Parameters

Return value

This function can return one of these values.

Return codeDescription
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.

 

 

///
        size_t len = urls[0].length();//获取字符串长度
        int nmlen = MultiByteToWideChar(CP_ACP, 0, urls[0].c_str(), len + 1, NULL, 0);//如果函数运行成功,并且cchWideChar为零,
                                                                                  //返回值是接收到待转换字符串的缓冲区所需求的宽字符数大小。
        wchar_t* buffer = new wchar_t[nmlen];
        MultiByteToWideChar(CP_ACP, 0, urls[0].c_str(), len + 1, buffer, nmlen);


        string savepath = "C:\\Users\\lenovo\\Desktop\\csvfile\\query_result0423\\"+imgname;
        size_t len1 = savepath.length();
        wchar_t* imgsavepath = new wchar_t[len1];
        int nmlen1 = MultiByteToWideChar(CP_ACP, 0, savepath.c_str(), len1 + 1, NULL, 0);
        MultiByteToWideChar(CP_ACP, 0, savepath.c_str(), len1 + 1, imgsavepath, nmlen1);
        
        
        HRESULT hr = URLDownloadToFile(NULL, buffer, imgsavepath, 0, NULL);
        if (hr == S_OK)
        {
            cout << "-------ok" << endl;
        }

技术分享图片

 

参考:

http://www.cnblogs.com/codingmengmeng/p/6258020.html

https://docs.microsoft.com/en-us/previous-versions/windows/internet-explorer/ie-developer/platform-apis/ms775123(v=vs.85)#parameters

评论(0
© 2014 mamicode.com 版权所有 京ICP备13008772号-2  联系我们:gaon5@hotmail.com
迷上了代码!