You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用Python将Ajax上传的Base64格式文本文件转为PNG图片

将Base64编码的PNG文本文件转换为PNG图片的Python实现

实现步骤

  1. 读取存储Base64数据的.txt文件内容
  2. 剥离Base64字符串开头的data:image/png;base64,标识前缀
  3. 对纯Base64编码数据进行二进制解码
  4. 将解码后的二进制流写入.png格式文件

完整代码示例

import base64

# 读取输入的txt文件
with open('input_image.txt', 'r') as txt_file:
    raw_content = txt_file.read().strip()

# 处理Base64前缀
if raw_content.startswith('data:image/png;base64,'):
    base64_content = raw_content.split(',')[1]
else:
    base64_content = raw_content

# 解码并生成PNG文件
try:
    png_binary = base64.b64decode(base64_content)
    with open('output_image.png', 'wb') as png_file:
        png_file.write(png_binary)
    print("图片转换成功,已保存为output_image.png")
except base64.binascii.Error as decode_err:
    print(f"解码失败:{decode_err}")
except IOError as file_err:
    print(f"文件操作错误:{file_err}")

注意事项

  • 文件模式:读取文本文件用r模式,写入图片必须使用wb二进制模式,防止字符编码导致的图片损坏
  • 前缀校验:必须移除data:image/png;base64,前缀,否则Base64解码会抛出异常
  • 异常处理:加入解码和文件操作的异常捕获,提升程序稳定性
  • 空白清理:使用strip()移除文本首尾的换行、空格等无效字符,避免解码错误

内容的提问来源于stack exchange,提问作者Effe Pelosa

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.15 08:40:31