pythonpython-imaging-librarywxpython

How to convert PIL image to wximage in Python 3


Hours of searching keep turning up this code:

mywxImage = wx.EmptyImage(*size*)
myPILImageRGB = MyPILImage.convert('RGB')
myPILImageData = MyPILImageRGB.tostring()
mywxImage.SetData(myPILImageData)

But MyPILImageRGB doesn't seem to have a tostring() method.

What I'm trying to do is display images in a Python program without using an external application.


Solution

  • You do not need to use the tostring method at all.

    This code converts a pil image to a bitmap and creates a wxImage on the way

    def static_bitmap_from_pil_image(self, pil_image):
        wx_image = wx.Image(pil_image.size[0], pil_image.size[1])
        wx_image.SetData(pil_image.convert("RGB").tobytes())
    
        bitmap = wx.Bitmap(wx_image)
        static_bitmap = wx.StaticBitmap(self, wx.ID_ANY, wx.NullBitmap)
        static_bitmap.SetBitmap(bitmap)
        return static_bitmap