使用C++下载URL图片

使用curl有些URL会下载失败,即下载下来的图片是空的。
使用下面方法,亲测有效。另外string转LPCWSTR时也可以参考。

#include <urlmon.h>
#pragma comment(lib,"urlmon.lib")

bool DownloadUrlmon(string strURL, string strPath)
{
    
    
	size_t len0 = strURL.length();
	int nmlen0 = MultiByteToWideChar(CP_ACP, 0, strURL.c_str(), len0 + 1, NULL, 0);
	wchar_t* bufferURL = new wchar_t[nmlen0];
	MultiByteToWideChar(CP_ACP, 0, strURL.c_str(), len0 + 1, bufferURL, nmlen0);
	size_t len1 = strURL.length();
	int nmlen1 = MultiByteToWideChar(CP_ACP, 0, strURL.c_str(), len1 + 1, NULL, 0);
	wchar_t* bufferPath = new wchar_t[nmlen1];
	MultiByteToWideChar(CP_ACP, 0, strPath.c_str(), len1 + 1, bufferPath, nmlen1);
	HRESULT hr = URLDownloadToFile(NULL, bufferURL, bufferPath, 0, NULL);
	if (hr != S_OK)
		return false;
	return true;
}

string strPathImageR1 = "https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fjunshi-pic.china.com%2Fhandcover%2F202101%2F27%2F1611710230_78708400.jpg&refer=http%3A%2F%2Fjunshi-pic.china.com&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=jpeg?sec=1614339658&t=ee65a9a5a9d07469ebfa8d70f87b244b";
string strPathImage1 = R"(aaa.png)";
DownloadUrlmon(strPathImageR1, strPathImage1);

猜你喜欢

转载自blog.csdn.net/Stone_Wang_MZ/article/details/121268030