Create a gtk.gdk.Pixbuf from binary data

2.1k views Asked by At

I am struggling to get binary data into a gtk.gdk.pixbuf.

This should illuminate my problem:

file = open("image.jpg", "rb")
//Ultimately this is going to come from a BLOB
binary = f.read()
//I created a pixbuf directly from the jpg 
//and took the rowstride values &c. from that
pixbuf = gtk.gdk.pixbuf_new_from_data(
    binary, gtk.gdk.COLORSPACE_RGB, False, 8 , 450, 640, 1352)

This fails with:

ValueError: data length (90825) is less then required by the other parameters (865280)

My current workaround is to write the binary data to a file and then create a Pixbuf from that file. That just feels so hacky. I am reading the binary data from a database so I really need a solution that can create a pixbuf straight from the buffer.

I don't understand why it's easy if I just read the BLOB from the database and write it to a file - then load the file as a pixbuf, but harder to go straight from the buffer!

What am I doing wrong?

1

There are 1 answers

0
Sebastian Werk On BEST ANSWER

You are trying to process jpg-data with a method made for RGB-data only.

If you want to process jpgs, use a loader for this format, as suggested here:

file = open("image.jpg", "rb")
binary = file.read()
loader = gtk.gdk.PixbufLoader("jpeg")
loader.write(binary)
loader.close()
pixbuf = loader.get_pixbuf()

Now pixbuf contains, what you need. Your workaround used such a loader automatically.