Python实现图片和base64转换详解
作者:祺稷
这篇文章主要介绍了Python实现图片和base64转换详解,Base64是一种二进制到文本的编码方式,如果要更具体一点的话,可以认为它是一种将 byte数组编码为字符串的方法,而且编码出的字符串只包含ASCII基础字符,需要的朋友可以参考下
Python图片转换
工作中很多时候使用图片和base64相互转换的地方,下面介绍转换代码
引用
import base64 from PIL import Image from io import BytesIO
base64转图片
方法, 入参base64串,及图片路径
转换后把图片存储在图片路径中。
def base64_to_images(base64_str,image_path):
# 将base64字符串解码为字节
image_data = base64.b64decode(base64_str)
# 将字节数据转换为图像
image = Image.open(BytesIO(image_data))
# 保存图像到本地
image.save(image_path)
图片转base64
方法 由于生产base64太长,存储到txt中。
入参:图片路径
txt路径:转换成base64存储在txt文件中
def image_to_base64(image_path,txt_path):
# 打开图像文件
with open(image_path, 'rb') as f:
# 读取图像文件内容
image_data = f.read()
# 将图像数据编码为base64字符串
base64_str = base64.b64encode(image_data)
with open(txt_path,'wb') as txt_file:
txt_file.write(base64_str)
调用
if __name__ == "__main__":
base64_str = "your base64 str"
image_path = "E:\\temp\\ggg.jpg"
# base64_to_images(base64_str=base64_str,image_path=image_path)
print('image saved')
txt_path = "E:\\temp\\ggg.txt"
image_to_base64(image_path,txt_path=txt_path)
print('base64 saved')
到此这篇关于Python实现图片和base64转换详解的文章就介绍到这了,更多相关Python图片转换内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!
