Pickle a GdkPixbuf.Pixbuf object in Python3



我想在 Python3 中腌制和取消腌制一个GdkPixbuf.Pixbuf。更具体地说,Python3 的multiprocessing包需要这样做,因为我通过Queue在进程之间共享此类对象。

问题是对象从

<GdkPixbuf.Pixbuf object at 0x7f8b9e9cfb88 (GdkPixbuf at 0x563b61725c60)>

<GdkPixbuf.Pixbuf object at 0x7f8b9e9eaea0 (uninitialized at 0x(nil))>

这是最低限度的工作示例。

>>> import gi
>>> from gi.repository import GdkPixbuf
__main__:1: PyGIWarning: GdkPixbuf was imported without specifying a version first. Use gi.require_version('GdkPixbuf', '2.0') before import to ensure that the right version gets loaded.
>>> pf = GdkPixbuf.Pixbuf.new_from_file('_icon.png')
>>> pf
<GdkPixbuf.Pixbuf object at 0x7f8b9e9cfb88 (GdkPixbuf at 0x563b61725c60)>
>>> import pickle
>>> pickle.dump(pf, open('p', 'wb'))
>>> pb2 = pickle.load(open('p', 'rb'))
>>> pb2
<GdkPixbuf.Pixbuf object at 0x7f8b9e9eaea0 (uninitialized at 0x(nil))>

我看不出有其他腌制的方法。图标需要加载到单独的进程中(在不同的 CPU 内核上,然后是应用程序主/第一个进程),然后应传输到主进程。这是通过一个处理所有数据的Queue完成的。

我的解决方案不是将"图标"作为内存中的Pixbuf对象,而是作为我从文件中读取的原始字节。

解开这些字节后,我将它们转换为Pixbuf

>>> import gi
>>> from gi.repository import GdkPixbuf, Gio, GLib
__main__:1: PyGIWarning: GdkPixbuf was imported without specifying a version first. Use gi.require_version('GdkPixbuf', '2.0') before import to ensure that the right version gets loaded.
>>> with open('_icon.png', 'rb') as f:
...     icon_bytes = f.read()
... 
>>> 
>>> import pickle
>>> pickle.dump(icon_bytes, open('p', 'wb'))
>>> 
>>> pb = pickle.load(open('p', 'rb'))
>>> pb = GLib.Bytes(pb)
>>> pb = GdkPixbuf.Pixbuf.new_from_stream(Gio.MemoryInputStream.new_from_bytes(pb))
>>> pb
<GdkPixbuf.Pixbuf object at 0x7fc0858ac5e8 (GdkPixbuf at 0x55e0d8d08b60)>

相关内容

  • 没有找到相关文章

最新更新