简体   繁体   English

如何使用 libcurl 保存图像

[英]How to save image using libcurl

I wanted to use libcurl for a project which involves getting an image from a webpage.我想将 libcurl 用于涉及从网页获取图像的项目。 The URL looks like this: URL 看起来像这样:

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

Using command-line cURL I can retrieve the image using使用命令行 cURL 我可以使用检索图像

$curl -o sampleimage.jpg http://xxx.xxx.xxx.xxx/cgi-bin/anonymous/image.jpg

I want to know the equivalent of this code in libcurl because I'm getting nuts right now.我想知道 libcurl 中这段代码的等价物,因为我现在疯了。 I got this sample source on the net, and it compiles and stuff, but I can't see the image file anywhere.我在网上得到了这个示例源,它可以编译和填充,但我在任何地方都看不到图像文件。

This is the code:这是代码:

#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; 
} 

BTW I'm using a Mac and I'm compiling this code on XCode which has a libcurl library.顺便说一句,我使用的是 Mac,我正在 XCode 上编译此代码,它有一个 libcurl 库。

* EDIT: *Problem fixed. *编辑: *问题已修复。 I just used a full path for the fopen().我只是为 fopen() 使用了完整路径。 Thanks Mat.谢谢马特。 Please answer the question so that I can choose yours as the correct answer.请回答问题,以便我选择您的问题作为正确答案。 Thanks!谢谢!

Use a full path in the open call so that you know where to look.在公开调用中使用完整路径,以便您知道在哪里查找。

Also you should look at the perror function so you can print the reason why the open fails when it does - saves a few headaches.您还应该查看错误perror以便打印打开失败的原因 - 省去一些麻烦。

Last thing: initialize fp to null, or only fclose(fp) if it was really open.最后一件事:将fp初始化为 null,或者只有fclose(fp)如果它真的打开了。 As it stands, if curl_easy_init fails, you'll attempt to fclose a random pointer.就目前而言,如果curl_easy_init失败,您将尝试fclose随机指针。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM