【问题标题】:How to get a PIL image as a Base64 encoded string如何将 PIL 图像作为 Base64 编码字符串获取
【发布时间】:2017-02-28 08:47:53
【问题描述】:

在过去的几个小时里,我一直在尝试创建一个图像的 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 编码数据的位在哪里?
  • @AlastairMcCormack 所说的,您正在使用 base64.b64decode(im) 对图像进行编码
  • @Robert 我的错误,错误的方法^^ 仍然 b64encode 给出相同的异常
  • 那么你现在解码的位在哪里?
  • 您的字符串解码良好,并在 bash 提示符中:echo "iVBORw0KGgoAAAANSUhEUgAAAGQAAABkCAIAAAD/gAIDAAAAbElEQVR4nO3Q0QmAMBAFwWitKSvFWsOKECIz/8c7dgwAAAAAAAAAAAAAADjHtW15zve3a333R3BvWT2UWIFYgViBWIFYgViBWIFYgViBWIFYgViBWIFYgViBWIFYgVgAAAAAAAAAAAAAAPBTD1i3AiiQSFCiAAAAAElFTkSuQmCC" | base64 -D > test.png。你需要encodedecode

标签: python python-3.x base64 python-imaging-library


【解决方案1】:

您需要在解码之前进行 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中字节表示的b''前缀所以我首先必须将它转换为字符串,然后切掉前几个字符。对于任何好奇的人:base = base64.b64encode(im) base.decode() base = str(base) base = base[2:len(base)- 1] 为我做的
  • 不,不。这是错误的做法。您只需使用“ascii”将字节对象作为文本decode()。结果是一个str。查看更新的答案。
【解决方案2】:

Image.frombytes() 不会从 base64 编码字符串创建图像,请参阅documentation

如果要反转编码,请使用:

img2 = base64.b64decode(base)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-08-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多