要将Base64转换为PNG图像并显示,可以使用以下代码示例:
import base64
from PIL import Image
from io import BytesIO
base64_str = "your_base64_string" # 替换为实际的Base64字符串
# 解码Base64字符串
image_data = base64.b64decode(base64_str)
# 将图像数据加载到PIL图像对象中
image = Image.open(BytesIO(image_data))
# 显示图像
image.show()
请确保已经安装了Pillow
库(PIL
的Fork),可以使用pip install Pillow
进行安装。
在以上代码中,首先使用base64.b64decode()
函数将Base64字符串解码为图像数据。然后,使用BytesIO
类将图像数据加载到PIL图像对象中。最后,使用image.show()
方法显示图像。
如果仍然无法显示图像,可能是Base64字符串存在问题,或者图像数据格式不正确。此时可以尝试打印图像对象的一些属性,例如image.size
、image.format
等,来确定图像是否正确加载。