Laravel  
laravel
文档
数据库
架构
入门
php技术
    
Laravelphp
laravel / php / java / vue / mysql / linux / python / javascript / html / css / c++ / c#

python base64转图片

作者:ンц枫飄落   发布日期:2025-12-29   浏览:91

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)

解释说明:

  1. 导入模块:我们使用了 base64 模块来处理 Base64 编码的数据,BytesIO 来处理字节流,PIL.Image 来处理图像。
  2. 去掉前缀:Base64 编码的图片通常带有 MIME 类型前缀(如 data:image/png;base64,),我们需要去掉这部分前缀。
  3. 解码 Base64:使用 base64.b64decode 方法将 Base64 字符串解码为二进制数据。
  4. 转换为图像:使用 Image.open 方法将二进制数据转换为图像对象。
  5. 保存图像:使用 image.save 方法将图像保存到指定路径。

这个函数可以将 Base64 编码的图片字符串转换并保存为实际的图片文件。

上一篇:python float转str

下一篇:python 调用c++

大家都在看

python时间格式

pythoneval函数用法

python读取文件路径

staticmethod在python中有

python 保存json文件

python开发windows应用程序

python中len是什么意思

python ord和chr

python中的yield

python自定义异常

Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3

Laravel 中文站