有没有可能的方法来显示wxPython应用程序中base64数据中的图像?

问题描述 投票:1回答:1

你好,

我正在为我的最后一个高中项目制作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))


但是如果我调用该函数,它将显示非常模糊的图像,并且仅以黑+白显示

我非常感谢每一个回答

python-3.x base64 wxpython
1个回答
0
投票

[您已经关闭,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的一些内置功能

© www.soinside.com 2019 - 2024. All rights reserved.