【问题标题】:Conversion from wxImage to PIL image and vice versa in Python3.7在 Python3.7 中从 wxImage 转换为 PIL 图像,反之亦然
【发布时间】:2019-06-02 20:04:29
【问题描述】:

从Python2.7切换到Python3.7后,我在网上找到的转换方法已经不行了。

我尝试了几个建议。每次PIL图片库throw错误:

...site-pacakges\PIL\Image.py",第 812 行,在 frombytes s=d.decode(data) TypeError: 参数 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

【问题讨论】:

  • 我的回答或其他人是否解决了您的问题?如果是这样,请考虑接受它作为您的答案 - 通过单击计票旁边的空心对勾/复选标记。如果没有,请说出什么不起作用,以便我或其他人可以进一步为您提供帮助。谢谢。 meta.stackexchange.com/questions/5234/…

标签: wxpython python-imaging-library


【解决方案1】:

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

【讨论】:

    【解决方案2】:

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-10-24
      • 2014-01-23
      相关资源
      最近更新 更多