import base64
from io import BytesIO
from PIL import Image
def base64_to_image(base64_string, output_path):
# 去掉base64字符串前面的"data:image/png;base64,"等前缀
if ',' in base64_string:
base64_string = base64_string.split(',')[1]
# 解码base64字符串为二进制数据
image_data = base64.b64decode(base64_string)
# 将二进制数据转换为图像
image = Image.open(BytesIO(image_data))
# 保存图像到指定路径
image.save(output_path)
# 示例用法
base64_string = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUA..."
output_path = "output_image.png"
base64_to_image(base64_string, output_path)
base64 模块来处理 Base64 编码的数据,BytesIO 来处理字节流,PIL.Image 来处理图像。data:image/png;base64,),我们需要去掉这部分前缀。base64.b64decode 方法将 Base64 字符串解码为二进制数据。Image.open 方法将二进制数据转换为图像对象。image.save 方法将图像保存到指定路径。这个函数可以将 Base64 编码的图片字符串转换并保存为实际的图片文件。
上一篇:python float转str
下一篇:python 调用c++
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站