将PIL图像转换为wxPython位图图像

时间:2017-10-06 12:56:34

标签: python bitmap wxpython python-imaging-library

我可以加载JPEG图像,将其转换为位图并在wx应用程序中绘制它。然而,我很难将PIL图像对象转换为可以绘制到wx应用程序中的位图。

在线,我能找到的最佳建议是做一些像

这样的事情
wx.Bitmap(PIL_image.tobytes())

然而,这给了我以下错误

UnicodeDecodeError: 'utf-8' codec can't decode byte 0x80 in position 59: invalid start byte

UnicodeDecodeError: 'utf-8' codec can't decode byte 0xc8 in position 51: invalid continuation byte

有人对如何解决这一问题有一个很好的暗示吗?谢谢!

1 个答案:

答案 0 :(得分:2)

互联网上有关于如何做到这一点的例子。但是有些条件没有涵盖在其中。 特别是在将wxBitmap()转换回PIL Image()时。

我在这里发布这些功能的修改版本。转换快速可靠。



from PIL import Image
import wx

def PIL2wx (image):
    width, height = image.size
    return wx.BitmapFromBuffer(width, height, image.tobytes())

def wx2PIL (bitmap):
    size = tuple(bitmap.GetSize())
    try:
        buf = size[0]*size[1]*3*"\x00"
        bitmap.CopyToBuffer(buf)
    except:
        del buf
        buf = bitmap.ConvertToImage().GetData()
    return Image.frombuffer("RGB", size, buf, "raw", "RGB", 0, 1)


# Suggested usage is to put the code in a separate file called
# helpers.py and use it as this:

from helpers import wx2PIL, PIL2wx
from PIL import Image

i = Image.open("someimage.jpg").convert("RGB")
wxb = PIL2wx(i)
# Now draw wxb to screen and let user draw something over it using wxDC() and so on...
# Then pick a wx.Bitmap() from wx.DC() and do something like:
wx2PIL(thedc.GetAsBitmap()).save("some new image.jpg")