使用libCurl和GdkPixBuff将图像从JPEG保存为PNG

Save an image from JPEG to PNG using libCurl and GdkPixBuff

本文关键字:JPEG 保存 PNG 图像 libCurl GdkPixBuff 使用      更新时间:2023-10-16

我正在尝试构建一种算法,从URL下载JPEG图像并将其作为PNG保存到磁盘中。为了实现这一点,我使用了libCurl进行下载,并使用了GdkPixbuff库进行其他内容(由于项目限制,我坚持使用Gdk库)

这里的代码实现数据:

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

其中上下文的定义如下:

struct context
{
unsigned char *data;
int allocation_size;
int length;
};

以这种方式写入DownloadedPic

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) failedn", ctx->allocation_size);
return -1;
}
}
if(ctx->length + nmemb > ctx->allocation_size)
{
fprintf(stderr, "fulln");
return -1;
}
memcpy(ctx->data + ctx->length, buffer, nmemb);
ctx->length += nmemb;
return nmemb;
}

最后我试着用这种方式保存图像:

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);

但是,我得到的是一张带有一堆随机像素的missy png图像,根本没有形状。现在,我确实知道图像的尺寸、宽度和高度,但我认为我对RowStride做了一些处理,我将其计算为width*3。

我哪里错了?

gdk_pixbuf_new_from_data不支持JPEG格式。您必须先将JPEG保存到一个文件中,然后用gdk_pixbuf_new_from_file加载它。或者在ctx.data周围创建一个GInputStream并使用gdk_pixbuf_new_from_stream