Save an image from JPEG to PNG using libCurl and GdkPixBuff
Question
I'm trying to build up an algorithm that downloads a JPEG image from an URL and saves it as a PNG into the disk. To achieve this I've used libCurl, for download, and GdkPixbuff library for the other stuffs (for a project limitation I'm sticked to Gdk libraries)
Here the code to achieve data:
CURL *curl;
GError *error = NULL;
struct context ctx;
memset(&ctx, 0, sizeof(struct context));
curl = curl_easy_init();
if(curl) {
curl_easy_setopt(curl, CURLOPT_URL, *file_to_download*);
curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, writeDownloadedPic);
curl_easy_setopt(curl, CURLOPT_WRITEDATA, &ctx);
curl_easy_perform(curl);
curl_easy_cleanup(curl);
}
where context is defined like that:
struct context
{
unsigned char *data;
int allocation_size;
int length;
};
and writeDownloadedPic in this way:
size_t writeDownloadedPic (void *buffer, size_t size, size_t nmemb, void *userp)
{
struct context *ctx = (struct context *) userp;
if(ctx->data == NULL)
{
ctx->allocation_size = 31014;
if((ctx->data = (unsigned char *) malloc(ctx->allocation_size)) == NULL)
{
fprintf(stderr, "malloc(%d) failed\n", ctx->allocation_size);
return -1;
}
}
if(ctx->length + nmemb > ctx->allocation_size)
{
fprintf(stderr, "full\n");
return -1;
}
memcpy(ctx->data + ctx->length, buffer, nmemb);
ctx->length += nmemb;
return nmemb;
}
and in the end I try to save the image in that way:
GdkPixbuf *pixbuf;
pixbuf = gdk_pixbuf_new_from_data(ctx.data,
GDK_COLORSPACE_RGB,
FALSE, 8,
222, 310,
222 * 3,
NULL, NULL);
gdk_pixbuf_save(pixbuf, "src/pics/image.png", "png", &error, NULL);
but, what I got is a missy png image with a bunch of random pixel and not form at all. Now, I know for sure dimension of image, width and height, but I think I've done some mess with the RowStride which I've calculated as width * 3.
Where am I wrong?
La solution
gdk_pixbuf_new_from_data
doesn't support JPEG format. You will either have to save the JPEG to a file first and load it with gdk_pixbuf_new_from_file
. Or create a GInputStream
around ctx.data
and use gdk_pixbuf_new_from_stream
.