Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ValueError while trying to save a pixmap as a png file

Tags:

python

gtk

pixmap

How can I save a pixmap as a .png file?
I do this:

    image = gtk.Image()
    image.set_from_pixmap(disp.pixmap, disp.mask)
    pixbf=image.get_pixbuf()
    pixbf.save('path.png')

I get this error:

    pixbf=image.get_pixbuf()
    ValueError: image should be a GdkPixbuf or empty
like image 596
Hesam Avatar asked Mar 15 '15 08:03

Hesam


3 Answers

From the documentation,

The get_pixbuf() method gets the gtk.gdk.Pixbuf being displayed by the gtk.Image. The return value may be None if no image data is set. If the storage type of the image is not either gtk.IMAGE_EMPTY or gtk.IMAGE_PIXBUF the ValueError exception will be raised.

(Emphasis Mine)

As you need a png file, You can follow the instructions from here

pixbuf = gtk.gdk.Pixbuf(gtk.gdk.COLORSPACE_RGB,has_alpha=False, bits_per_sample=8, width=width, height=height)
pixbuf.get_from_drawable(disp.pixmap, disp.pixmap.get_colormap(), 0, 0, 0, 0, width, height)
pixbuf.save('path.png')

This will create a pixbuf from your pixmap which is disp.pixmap. This can be later saved using pixbuf.save

like image 192
Bhargav Rao Avatar answered Nov 17 '22 14:11

Bhargav Rao


In these cases it is useful to read the documentation from Gtk itself, instead of the PyGtk, as they are more complete.

In this case the relevant functions are gtk_image_set_from_pixmap() and gtk_image_get_pixbuf():

Gets the GdkPixbuf being displayed by the GtkImage. The storage type of the image must be GTK_IMAGE_EMPTY or GTK_IMAGE_PIXBUF.

The problem is that the GtkImage widget can hold both a GdkPixbuf, a GdkPixmap, a GdkImage... but it cannot convert between them, that is, you can only recover what you stored.

You are storing a pixmap and trying to get a pixbuf, and that will not work. Now, what is the solution? That depends on what you are trying to do exactly. Probably it is enough if you convert it to a pixbuf with gtk.pixbuf.get_from_drawable():

w,h = disp.pixmap.get_size()
pb = gtk.gdk.Pixbuf(gtk.gdk.COLORSPACE_RGB, True, 8, w, h)
pb.get_from_drawable(disp.pixmap, disp.pixmap.get_colormap(),
    0, 0, 0, 0, width, height)
pb.save('path.png')
like image 31
rodrigo Avatar answered Nov 17 '22 14:11

rodrigo


While waiting for the answer I actually found the solution

pixbuf = gtk.gdk.Pixbuf(gtk.gdk.COLORSPACE_RGB, False, 8, width, height)
pixbf = pixbuf.get_from_drawable(disp.pixmap, disp.pixmap.get_colormap(), 0, 0, 0, 0, width, height)
pixbf.save('path.png')

assuming disp.pixmap is your pixmap object

like image 34
Tadej Magajna Avatar answered Nov 17 '22 13:11

Tadej Magajna