在python中如何将Image模块生成的图片直接转为base64?

  • Post author:
  • Post category:python


可以使用base64模块,通过base64.b64encode()函数可以将图片直接转换为base64编码。

from io import BytesIO 
from PIL import Image 
import base64 

# 创建一个图片
image = Image.new("RGB",(100,100)) 

# 将图片写入BytesIO
img_io = BytesIO() 
image.save(img_io, 'JPEG') # 保存图片

# 从BytesIO中获取图片数据
img_byte = img_io.getvalue()

# 将图片转换为base64格式
img_base64 = base64.b64encode(img_byte)

# 将base64编码转换为字符串
img_base64_str = img_base64.decode('utf-8')

print(img_base64_str)



版权声明:本文为qq_39653624原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。