Conversion from wxImage to PIL image and vice versa in Python3.7

Viewed 565

After switching from Python2.7 to Python3.7 the conversion methods I found in the internet are not working anymore.

I tried several proposals. Everytime the PIL image library thorws an error:

...site-pacakges\PIL\Image.py", line 812, in frombytes s=d.decode(data) TypeError: argument 1 must be read-only bytes-like object, not 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 Answers

I don't use wxPython at all, but this seems to work:

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))

You have to use myWxImage.GetDataBuffer() instead of GetData()

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