如何获取PIL图像作为Base64编码的字符串 [英] How to get a PIL image as a Base64 encoded string

查看:500
本文介绍了如何获取PIL图像作为Base64编码的字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在过去的几个小时中,我一直在尝试创建Image的Base64字符串,但是它不起作用.

for the past few hours i've been trying to create a Base64 String of an Image, but it won't work.

ship_color = (0,100,100,255)
img = Image.new("RGBA", (100,100))
for i in range(20):
   for j in range(20):
       img.putpixel((40 + i, 40 + j), ship_color)
img.save("tmp.png", format = "PNG")
im = open("tmp.png", "rb").read()
print(im)
base = base64.b64encode(im)
print(base)

当我再次尝试从字符串创建图像时,出现异常:

When i try to create an image from the String again i get an exception:

img2 = Image.frombytes("RGBA", (100, 100), base)
ValueError: not enough image data

其他用于Base64解码的在线服务也给出了错误,因此base64字符串本身似乎并不正确.

Other online services for Base64 Decoding also give an error, so the base64 String itself does not seem to be correct.

示例图片字符串(来自open().read()):

example image String (from open().read()):

b'\x89PNG\r\n\x1a\n\x00\x00\x00\rIHDR\x00\x00\x00d\x00\x00\x00d\x08\x02\x00\x00\x00\xff\x80\x02\x03\x00\x00\x00lIDATx\x9c\xed\xd0\xd1\t\x800\x10\x05\xc1h\xad)+\xc5Z\xc3\x8a\x10"3\xff\xc7;v\x0c\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x008\xc7\xb5my\xce\xf7\xb7k}\xf7GpoY=\x94X\x81X\x81X\x81X\x81X\x81X\x81X\x81X\x81X\x81X\x81X\x81X\x81X\x81X\x81X\x81X\x81X\x81X\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\xf0S\x0fX\xb7\x02(\x90HP\xa2\x00\x00\x00\x00IEND\xaeB`\x82'

示例base64字符串:

example base64 String:

b'iVBORw0KGgoAAAANSUhEUgAAAGQAAABkCAIAAAD/gAIDAAAAbElEQVR4nO3Q0QmAMBAFwWitKSvFWsOKECIz/8c7dgwAAAAAAAAAAAAAADjHtW15zve3a333R3BvWT2UWIFYgViBWIFYgViBWIFYgViBWIFYgViBWIFYgViBWIFYgVgAAAAAAAAAAAAAAPBTD1i3AiiQSFCiAAAAAElFTkSuQmCC'

推荐答案

您需要对base64 编码进行解码.

You need to base64 encode before you can decode.

使用io.BytesIO()

in_mem_file = io.BytesIO()
img.save(in_mem_file, format = "PNG")
# reset file pointer to start
in_mem_file.seek(0)
img_bytes = in_mem_file.read()

base64_encoded_result_bytes = base64.b64encode(img_bytes)
base64_encoded_result_str = base64_encoded_result_bytes.decode('ascii')

这篇关于如何获取PIL图像作为Base64编码的字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆