尝试将像素图另存为 png 文件时出现 ValueError

ValueError while trying to save a pixmap as a png file

如何将像素图保存为 .png 文件?
我这样做:

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

我收到这个错误:

    pixbf=image.get_pixbuf()
    ValueError: image should be a GdkPixbuf or empty

在等待答案的过程中,我实际上找到了解决方案

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

假设 disp.pixmap 是您的像素图对象

来自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.

(强调我的)

因为你需要一个 png 文件,你可以按照 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')

这将从您的 pixmap 创建一个 pixbuf,即 disp.pixmap。稍后可以使用 pixbuf.save

保存

在这些情况下,阅读 Gtk 本身的文档而不是 PyGtk 的文档很有用,因为它们更完整。

在这种情况下,相关函数是 gtk_image_set_from_pixmap()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.

问题是 GtkImage 小部件可以容纳 GdkPixbufGdkPixmapGdkImage...但它不能在它们之间进行转换,即是,您只能恢复您存储的内容。

您正在存储一个像素图并试图获取一个 pixbuf,但这将不起作用。现在,解决方案是什么?这取决于你到底想做什么。如果你用 gtk.pixbuf.get_from_drawable():

将它转换成 pixbuf 可能就足够了
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')