Using GTK+ 3.6 I would like to display an image from a buffer in memory, not a file on disk. I have a const char *data
with the image data, and I'm trying to create a GTK image from it.
So far I have tried two approaches which I thought could work. Both use GdkPixbuf, and thus require the image data to be guchar* (unsigned char*)
.
With that requirement I have to cast the data:
guchar *gudata = reinterpret_cast<guchar*>(const_cast<char*>(data));
I then tried the following:
Writing the data into a GdkPixbufLoader with
gdk_pixbuf_loader_write
. Here I get an error"Unrecognized image file format"
or if I create the loader with a specific type (jpg) i get an error saying that it's not a JPG file format (and it is, explained below).EDIT: A bit of code:
guchar *gudata = reinterpret_cast<guchar*>(const_cast<char*>(data)); int stride = ((1056 * 32 + 31) & ~31)/8; GdkPixbufLoader *loader = gdk_pixbuf_loader_new(); GError *error = NULL; if(!gdk_pixbuf_loader_write(loader, gudata, data_size, &error) { printf("Error:\n%s\n", error->message); }
EDIT 03/01/2013: Removed stride parameter from write function - misprint.
Cairo surface does not work as well. Shows black screen and noise.
Initializing the pixbuf with
gdk_pixbuf_new_from_data
and then the image just looks like tv noise, which would indicate that either the data is wrong (and it has been cast), or that the other parameters were wrong (image row stride, but it's not :) ).
After errors I just tried writing the data to a file foo.jpg
using ofstream
and yes, I get a properly working image file. The file
command in terminal confirms that it is a JPEG image, and with a simple block of code I've created a GdkPixbuf from that foo.jpg to check out it's row stride value and it matches the value I pass to the aforementioned function.
Does the image data become corrupt with the cast, and if so how can I address that? I get the image data in const char*
. I have looked at QtPixmap and it also loads unsigned char*
.
Do I need to use a seperate library? (libjpeg?) I have libgtk3-dev installed.
Thank you!