converting a PIL image to wxPython bitmap image

Viewed 2935

I can load a JPEG image, convert it to bitmap and plot it in a wx application. I am having however a hard time in converting a PIL image object into a bitmap that can be plotted into a wx application.

Online, the best suggestion I could find is to do something like

wx.Bitmap(PIL_image.tobytes())

However, this gives me the following error

UnicodeDecodeError: 'utf-8' codec can't decode byte 0x80 in position 59: invalid start byte

or

UnicodeDecodeError: 'utf-8' codec can't decode byte 0xc8 in position 51: invalid continuation byte

Has someone a good hint on how to address this point? Thanks!

1 Answers

There are examples all over the internet on how to do it. But there are some conditions which aren't covered in them. Especially when converting wxBitmap() back to PIL Image().

I post here my modified versions of these functions. Conversion is fast and reliable.



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

Related