在Python3.7中从wxImage转换为PIL图像,反之亦然

时间:2019-01-08 06:49:32

标签: wxpython python-imaging-library

从Python2.7切换到Python3.7后,我在互联网上发现的转换方法不再起作用。

我尝试了几个建议。每次PIL图片库都出现错误时:

  

... site-pacakges \ PIL \ Image.py“,第812行,以frombytes s = d.decode(data)为单位   TypeError:参数1必须是类似字节的只读对象,而不是bytearray

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

2 个答案:

答案 0 :(得分:0)

我根本不使用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))

答案 1 :(得分:0)

您必须使用myWxImage.GetDataBuffer()而不是GetData()

>>> type(img.GetData())
<type 'str'>
>>> type(img.GetDataBuffer())
<type 'buffer'>