如何使用libcurl保存图像

How to save image using libcurl

本文关键字:图像 保存 libcurl 何使用      更新时间:2023-10-16

我想使用libcurl的一个项目,涉及从网页获取图像。URL看起来像这样:

http://xxx.xxx.xxx.xxx/cgi-bin/anonymous/image.jpg

使用命令行cURL可以使用

检索图像
$curl -o sampleimage.jpg http://xxx.xxx.xxx.xxx/cgi-bin/anonymous/image.jpg

我想知道这段代码在libcurl中的等价,因为我现在快疯了。我在网上找到了这个示例源代码,它可以编译,但是我在任何地方都看不到图像文件。

这是代码:

#include <iostream> 
#include <curl/curl.h> 
#include <stdio.h> 
using namespace std; 
int main(){ 
CURL *image; 
CURLcode imgresult; 
FILE *fp; 
image = curl_easy_init(); 
if( image ){ 
    // Open file 
    fp = fopen("google.jpg", "wb"); 
    if( fp == NULL ) cout << "File cannot be opened"; 
    curl_easy_setopt(image, CURLOPT_URL, "http://192.168.16.25/cgi-bin/viewer/video.jpg"); 
    curl_easy_setopt(image, CURLOPT_WRITEFUNCTION, NULL); 
    curl_easy_setopt(image, CURLOPT_WRITEDATA, fp); 

    // Grab image 
    imgresult = curl_easy_perform(image); 
    if( imgresult ){ 
        cout << "Cannot grab the image!n"; 
    } 
} 
// Clean up the resources 
curl_easy_cleanup(image); 
// Close the file 
fclose(fp); 
return 0; 
} 

顺便说一句,我用的是Mac电脑,我在XCode上编译这段代码,XCode有一个libcurl库。

* 编辑: *固定问题。我只是为fopen()使用了一个完整的路径。谢谢垫!请回答问题,以便我选择你的作为正确答案。谢谢!

在open call中使用完整路径,以便您知道在哪里查找。

你还应该看看perror函数,这样你就可以打印出打开失败的原因——节省了一些麻烦。

最后一件事:初始化fp为null,或者只有fclose(fp),如果它真的是打开的。目前,如果curl_easy_init失败,您将尝试fclose一个随机指针。