你好,
我正在为我的最后一个高中项目制作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))
但是如果我调用该函数,它将显示非常模糊的图像,并且仅显示为黑+白
我非常感谢每个答案
答案 0 :(得分:3)
您接近了,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
的一些内置功能。