如何用Python将Ajax上传的Base64格式文本文件转为PNG图片
将Base64编码的PNG文本文件转换为PNG图片的Python实现
实现步骤
- 读取存储Base64数据的.txt文件内容
- 剥离Base64字符串开头的
data:image/png;base64,标识前缀 - 对纯Base64编码数据进行二进制解码
- 将解码后的二进制流写入.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
相关产品推荐
相关产品推荐

