在过去的几个小时里,我一直在尝试创建图像的 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)
当我再次尝试从字符串创建图像时出现异常:
img2 = Image.frombytes("RGBA", (100, 100), base)
ValueError: not enough image data
网上其他服务Base64 Decoding也报错,所以base64 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'
示例 base64 字符串:
b'iVBORw0KGgoAAAANSUhEUgAAAGQAAABkCAIAAAD/gAIDAAAAbElEQVR4nO3Q0QmAMBAFwWitKSvFWsOKECIz/8c7dgwAAAAAAAAAAAAAADjHtW15zve3a333R3BvWT2UWIFYgViBWIFYgViBWIFYgViBWIFYgViBWIFYgViBWIFYgVgAAAAAAAAAAAAAAPBTD1i3AiiQSFCiAAAAAElFTkSuQmCC'
最佳答案
您需要先进行 base64 编码,然后才能解码。
您可以通过使用内存中的文件和 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')
关于python - 如何获取 PIL 图像作为 Base64 编码的字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42503995/