Renecekk
Renecekk

Reputation: 77

Is there any possible way how to show image from base64 data in wxPython app?

Hello,

I am making a python3 application for my final High School project and I experienced some troubles. If I want to show any images in my app, I have to place them to the specified directory and what I would like to do is just get the base64 strings from each image, place it into my code and just load the images from these strings. This could make my app portable without any additional files to be copied as well.

I created few functions for that but no one works


import base64
from PIL import Image
from io import BytesIO

b64imgData = "iVBORw0KGgoAAAANSUhEUgAAA3QAAABMCAYAAAAlUfXmAAAABGdBTUEAALGPC/..."

decodedImgData = base64.b64decode(imgData)
bio = BytesIO(decodedImgData)
img = Image.open(bio)

and this was used to view image :

wx.StaticBitmap(panel, -1, img, (50, yHalf/14+20), (xHalf - 100, yHalf/8))

When I run the code I am getting this:

Traceback (most recent call last):
  File "C:\Users\dummy\Desktop\PWG\main.py", line 68, in OnInit
    frame = Menu()
  File "C:\Users\dummy\Desktop\PWG\main.py", line 127, in __init__
    wx.StaticBitmap(panel, -1, img, (50, yHalf/14+20), (xHalf - 100, yHalf/8))
TypeError: StaticBitmap(): arguments did not match any overloaded call:
  overload 1: too many arguments
  overload 2: argument 3 has unexpected type 'PngImageFile'
OnInit returned false, exiting...

My next attempt was :


#I used this function from another thread which looks that may work
def PIL2wx (image):
    width, height = image.size
    return wx.BitmapFromBuffer(width, height, image.tobytes())


import base64
from PIL import Image
from io import BytesIO

b64imgData = "iVBORw0KGgoAAAANSUhEUgAAA3QAAABMCAYAAAAlUfXmAAAABGdBTUEAALGPC/..."

decodedImgData = base64.b64decode(imgData)
bio = BytesIO(decodedImgData)
img = Image.open(bio)

finalImage = PIL2wx(img)

wx.StaticBitmap(panel, -1, finalImage, (50, yHalf/14+20), (xHalf - 100, yHalf/8))


but if I call the function, It shows the image very blurry and only in Black+white

I'm very thankful for every answer

Upvotes: 3

Views: 465

Answers (1)

user2682863
user2682863

Reputation: 3218

You were close, the bitmap argument of the wx.StaticBitmap must be a wx.Bitmap instead of a wx.Image. Try:

b64imgData = "iVBORw0KGgoAAAANSUhEUgAAA3QAAABMCAYAAAAlUfXmAAAABGdBTUEAALGPC/..."
decodedImgData = base64.b64decode(imgData)
bio = BytesIO(decodedImgData)
img = wx.Image(bio)
if not img.IsOk():
    raise ValueError("this is a bad/corrupt image")
# image scaling
width, height  = (xHalf - 100, yHalf/8)
img = img.Scale(width, height, wx.IMAGE_QUALITY_HIGH)  # type: wx.Image
# converting the wx.Image to wx.Bitmap for use in the StaticBitmap
bmp = img.ConvertToBitmap()  # type: wx.Bitmap
wx.StaticBitmap(panel, -1, bmp)

wxpython has some built-in functionality for this documented here

Upvotes: 4

Related Questions