有什么方法可以在 wxPython 应用程序中显示来自 base64 数据的图像吗?

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

你好,

我正在为我的高中期末项目申请 python3,我遇到了一些麻烦。如果我想在我的应用程序中显示任何图像,我必须将它们放在指定的目录中,我想做的只是从每个图像中获取 base64 字符串,将其放入我的代码中,然后从这些字符串中加载图像.这可以使我的应用程序可移植,而无需复制任何其他文件。

我为此创建了几个函数,但没有一个起作用


import base64
from PIL import Image
from io import BytesIO

b64imgData = "iVBORw0KGgoAAAANSUhEUgAAA3QAAABMCAYAAAAlUfXmAAAABGdBTUEAALGPC/..."

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

这是用来查看图片的:

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

当我 运行 我得到这个代码时:

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

我的下一次尝试是:


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


但如果我调用该函数,它显示的图像非常模糊,并且只有黑色和白色

非常感谢您的每一个回答

你很接近,wx.StaticBitmap 的位图参数必须是 wx.Bitmap 而不是 wx.Image。尝试:

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 有一些针对此记录的内置功能 here