简体   繁体   English

如何将PIL图像作为Base64编码的字符串

[英]How to get a PIL image as a Base64 encoded string

for the past few hours i've been trying to create a Base64 String of an Image, but it won't work. 在过去的几个小时里,我一直在尝试创建一个图像的Base64字符串,但它不起作用。

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

Other online services for Base64 Decoding also give an error, so the base64 String itself does not seem to be correct. Base64 Decoding的其他在线服务也会出错,因此base64字符串本身似乎不正确。

example image String (from open().read()): example image String(来自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'

example base64 String: 示例base64字符串:

b'iVBORw0KGgoAAAANSUhEUgAAAGQAAABkCAIAAAD/gAIDAAAAbElEQVR4nO3Q0QmAMBAFwWitKSvFWsOKECIz/8c7dgwAAAAAAAAAAAAAADjHtW15zve3a333R3BvWT2UWIFYgViBWIFYgViBWIFYgViBWIFYgViBWIFYgViBWIFYgVgAAAAAAAAAAAAAAPBTD1i3AiiQSFCiAAAAAElFTkSuQmCC'

You need to base64 encode before you can decode. 在解码之前,您需要base64 编码

You can achieve this without creating a temporary file by using an in memory file, with io.BytesIO() 您可以通过使用内存文件创建临时文件来实现此目的,使用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')

Image.frombytes() does not create an image from a base64 encoded string, see documentation . Image.frombytes()不会从base64编码的字符串创建图像,请参阅文档

If you want to reverse the encoding, use: 如果要反转编码,请使用:

img2 = base64.b64decode(base)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM