title: Gdk pixbuf load image from memory
body: <p>Using GTK+ 3.6 I would like to display an image from a buffer in memory, not a file on disk. I have a <code>const char *data</code> 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 <code>guchar* (unsigned char*)</code>.</p>
  
  <p>With that requirement I have to cast the data: </p>
  
  <pre><code>guchar *gudata = reinterpret_cast&lt;guchar*&gt;(const_cast&lt;char*&gt;(data));
  </code></pre>
  
  <p>I then tried the following:</p>
  
  <ol>
  <li><p>Writing the data into a GdkPixbufLoader with <code>gdk_pixbuf_loader_write</code>. Here I get an error <code>"Unrecognized image file format"</code> 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).</p>
  
  <p>EDIT: A bit of code:</p>
  
  <pre><code>guchar *gudata = reinterpret_cast&lt;guchar*&gt;(const_cast&lt;char*&gt;(data));
  int stride = ((1056 * 32 + 31) &amp; ~31)/8;
  GdkPixbufLoader *loader = gdk_pixbuf_loader_new();
  GError *error = NULL;
  
  if(!gdk_pixbuf_loader_write(loader, gudata, data_size, &amp;error)
  { 
      printf("Error:\n%s\n", error-&gt;message); 
  }
  </code></pre>
  
  <p>EDIT 03/01/2013: 
  Removed stride parameter from write function - misprint.</p>
  
  <p>Cairo surface does not work as well. Shows black screen and noise.</p></li>
  <li><p>Initializing the pixbuf with <code>gdk_pixbuf_new_from_data</code> 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 :) ).</p></li>
  </ol>
  
  <p>After errors I just tried writing the data to a file <code>foo.jpg</code> using <code>ofstream</code> and yes, I get a properly working image file. The <code>file</code> 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.</p>
  
  <p>Does the image data become corrupt with the cast, and if so how can I address that? I get the image data in <code>const char*</code>. I have looked at QtPixmap and it also loads <code>unsigned char*</code>.</p>
  
  <p>Do I need to use a seperate library? (libjpeg?)
  I have libgtk3-dev installed.</p>
  
  <p>Thank you!</p>