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

标签 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

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

最佳答案

互联网上到处都有关于如何做到这一点的示例。但有些条件并未涵盖其中。 特别是当将 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")

关于python - 将 PIL 图像转换为 wxPython 位图图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46606283/

相关文章:

android试图圆位图角

python - wxpython,将变量从一个框架导入到两个不同文件中的另一个框架

python - Py2app 阻止 wxpython 打开第二个 wx.Frame

python - 手动将 tf.contrib.slim 升级到 tf 2.0

python - 如何转义实际上名为 <parent> 的 BeautifulSoup ISO 标签中的父属性?

performance - EaselJS中大量动画位图的速度

c# - control.DrawToBitmap() 未按预期工作

python - wxPython:ListCtrl查找具有给定字符串的项目

python - Pandas Dataframe 合并列上的行以形成字典列表

python - 我怎样才能从 Twitter 用户那里获得大量关注者,然后关注他们?