Jam*_*mes 2 c c++ curl image download
我试图通过从服务器(网站)下载图像设置旋转背景图片,并试图与这样卷曲然而有0成功做到这一点.我的代码的(缩短版)如下所示.我没有收到错误,但是,如何"临时"保存此图像以将其显示为我的背景?有图像(-type变量)还是什么?
这只是一次学习经历,因此非常感谢任何图书馆或建议.
#include <curl/curl.h>
CURL *curlCtx = curl_easy_init();
curl_easy_setopt(curlCtx, CURLOPT_URL, "http://www.examplesite.com/testimage.jpeg");
curl_easy_setopt(curlCtx, CURLOPT_WRITEDATA, this);
curl_easy_setopt(curlCtx, CURLOPT_WRITEFUNCTION, callbackfunction);
const CURLcode rc = curl_easy_perform(curlCtx);
if(rc == CURLE_OK){
//it worked
}
size_t callbackfunction(char *data, size_t size, size_t nmemb, void *stream){
//do something here with image...?
}
Run Code Online (Sandbox Code Playgroud)
谢谢,詹姆斯
编辑:对不起我错误地添加了()回调函数.
您的代码甚至无法编译!URG!
本callbackfunction()应实施以处理传入的数据流.在这种情况下,我猜你想要将数据写入文件中,对吧?
检查呼叫的返回总是很好的做法,因此请采用我正在共享的源代码并仔细研究它.下面的程序完成了你想要做的事情.
dw.cpp:
#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;
}
Run Code Online (Sandbox Code Playgroud)
编译:g++ dw.cpp -o dw -lcurl并测试:
./dw http://unicornify.appspot.com/avatar/51d623f33f8b83095db84ff35e15dbe8?s=128
Run Code Online (Sandbox Code Playgroud)
此应用程序在磁盘中创建一个文件,该文件以其out.jpg下载的数据命名.