从Python2.7切换到Python3.7后,我在网上找到的转换方法不再起作用了。
我尝试了几个建议。每次PIL图像库都会出错:
...site-pacakges\PIL\Image.py",第 812 行,在 frombytes s=d.decode(data) 中 类型错误:参数 1 必须是只读字节类对象,而不是字节数组
def WxImageToPilImage1( myWxImage ):
"""Convert wx.Image to PIL Image."""
width, height = myWxImage.GetSize()
data = myWxImage.GetData()
red_image = Image.new("L", (width, height))
red_image.frombytes(data[0::3])
green_image = Image.new("L", (width, height))
green_image.frombytes(data[1::3])
blue_image = Image.new("L", (width, height))
blue_image.frombytes(data[2::3])
if myWxImage.HasAlpha():
alpha_image = Image.new("L", (width, height))
alpha_image.frombytes(myWxImage.GetAlphaData())
myPilImage = Image.merge('RGBA', (red_image, green_image, blue_image, alpha_image))
else:
myPilImage = Image.merge('RGB', (red_image, green_image, blue_image))
return myPilImage
def WxImageToPilImage2( myWxImage ):
myPilImage = Image.new( 'RGB', (myWxImage.GetWidth(), myWxImage.GetHeight()) )
myPilImage.frombytes( myWxImage.GetData() )
return myPilImage
我根本不使用
wxPython
,但这似乎有效:
import wx
app = wx.PySimpleApp()
wxim = wx.Image('start.png', wx.BITMAP_TYPE_ANY)
w = wxim.GetWidth()
h = wxim.GetHeight()
data = wxim.GetData()
red_image = Image.frombuffer('L',(w,h),data[0::3])
green_image = Image.frombuffer('L',(w,h),data[1::3])
blue_image = Image.frombuffer('L',(w,h),data[2::3])
myPilImage = Image.merge('RGB', (red_image, green_image, blue_image))
您必须使用
myWxImage.GetDataBuffer()
而不是 GetData()
>>> type(img.GetData())
<type 'str'>
>>> type(img.GetDataBuffer())
<type 'buffer'>
为了补充 Mark 的答案,如果您还需要 Alpha 通道数据(例如来自 wx.Clipboard):
import wx
app = wx.PySimpleApp()
wxim = wx.Image('start.png', wx.BITMAP_TYPE_ANY)
w = wxim.GetWidth()
h = wxim.GetHeight()
data = wxim.GetData()
red_image = Image.frombuffer('L',(w,h),data[0::3])
green_image = Image.frombuffer('L',(w,h),data[1::3])
blue_image = Image.frombuffer('L',(w,h),data[2::3])
myPilImage = Image.merge('RGB', (red_image, green_image, blue_image))
# Add alpha channel info:
if wxim.HasAlpha():
alpha_image = bytes(wxim.GetAlpha())
myPilImage = Image.merge('RGBA', (red_image, green_image, blue_image, alpha_image))