我正在做一个项目,它的第一步包括从网址下载图像并将其保存到某个位置。将在稍后阶段对该图像进行进一步处理。为此,我在视觉中使用curl库工作室和opencv。我是使用curl库的新手。我看到了答案here。但是,我无法理解。这是我的代码
#include <stdio.h>
#include <curl/curl.h>
#include <curl/types.h>
#include <curl/easy.h>
#include <string>
size_t write_data(void* ptr, size_t size, size_t nmemb, FILE* stream)
{
size_t written;
written = fwrite(ptr, size, nmemb, stream);
return written;
}
int main(void)
{
CURL* curl;
FILE* fp;
CURLcode res;
char* url = "http://pimg.tradeindia.com/01063301/b/1/CRO-Oscilloscope.jpg";
char outfilename[FILENAME_MAX] = "C:\\bbb.jpg";
curl = curl_easy_init();
if (curl)
{
fp = fopen(outfilename, "wb");
curl_easy_setopt(curl, CURLOPT_URL, url);
curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, write_data);
curl_easy_setopt(curl, CURLOPT_WRITEDATA, fp);
curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1L);
res = curl_easy_perform(curl);
/* always cleanup */
curl_easy_cleanup(curl);
fclose(fp);
}
return 0;
}
感谢您的帮助。
答案 0 :(得分:0)
#include <stdio.h>
#include <curl/curl.h>
size_t callbackfunction(void *ptr, size_t size, size_t nmemb, void* userdata)
{
FILE* stream = (FILE*)userdata;
if (!stream)
{
printf("!!! No stream\n");
return 0;
}
size_t written = fwrite((FILE*)ptr, size, nmemb, stream);
return written;
}
bool download_jpeg(char* url)
{
FILE* fp = fopen("out.jpg", "wb");
if (!fp)
{
printf("!!! Failed to create file on the disk\n");
return false;
}
CURL* curlCtx = curl_easy_init();
curl_easy_setopt(curlCtx, CURLOPT_URL, url);
curl_easy_setopt(curlCtx, CURLOPT_WRITEDATA, fp);
curl_easy_setopt(curlCtx, CURLOPT_WRITEFUNCTION, callbackfunction);
curl_easy_setopt(curlCtx, CURLOPT_FOLLOWLOCATION, 1);
CURLcode rc = curl_easy_perform(curlCtx);
if (rc)
{
printf("!!! Failed to download: %s\n", url);
return false;
}
long res_code = 0;
curl_easy_getinfo(curlCtx, CURLINFO_RESPONSE_CODE, &res_code);
if (!((res_code == 200 || res_code == 201) && rc != CURLE_ABORTED_BY_CALLBACK))
{
printf("!!! Response code: %d\n", res_code);
return false;
}
curl_easy_cleanup(curlCtx);
fclose(fp);
return true;
}
int main(int argc, char** argv)
{
if (argc < 2)
{
printf("Usage: %s <url>\n", argv[0]);
return -1;
}
if (!download_jpeg(argv[1]))
{
printf("!! Failed to download file: %s\n", argv[1]);
return -1;
}
return 0;
}
这个怎么样?
答案 1 :(得分:0)
我不了解argc和argv方面的代码。你能解释一下吗? - 约翰史密斯
他们在启动程序时习惯于传递命令行参数。 argv是指向cstrings数组的双指针,argc是cstrings的数量。在这种情况下,argv [0]将是可执行文件的名称,而argv [1]将是要下载的映像的URL。即foo.exe http://path/to/image.jpg