Python3 将 Base64 图片字符串转换为图片
可以使用 Python 标准库中的 base64 和 PIL 库来实现将 base64 图片字符串转换成图片。
示例代码:
import base64
from PIL import Image
from io import BytesIO
# base64 图片字符串
img_string = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUA...'
# 去掉前缀
img_data = img_string.split(',')[1]
# base64 解码
img_binary = base64.b64decode(img_data)
# 读取为 PIL 格式图片
img = Image.open(BytesIO(img_binary))
# 显示图片
img.show()
解释:
- 导入需要的库:base64 用来解码 base64 字符串,PIL 用来处理图片,BytesIO 用来将二进制数据转换成文件对象。
- 定义 base64 图片字符串。
- 从字符串中提取图片数据部分。
- 使用 base64 解码得到二进制数据。
- 使用 PIL 库的 Image.open 方法读取二进制数据为图片对象。
- 使用 PIL 库的 show 方法显示图片。可以使用其他方法来保存图片到文件或者进行其他操作。
原文地址: https://www.cveoy.top/t/topic/lEyj 著作权归作者所有。请勿转载和采集!