繁体   English   中英

在 Python 中编码 base64 中的 PNG 图像

[英]Encode PNG image in base64 in Python

我有一些 Python 代码可以生成 PNG 格式的动态图像。 这可以正常工作,因为我可以将字节保存到磁盘并获得有效的 PNG 图像。 然后我尝试对 base64 中的字节进行编码,并将它们传递给 HTML 模板(在 Django 网站中)以渲染图像。 这是可以做到的,因为如果我传递一个已知正确的 base64 字符串,我就可以让它工作。 但它不适用于我的字符串,可能是因为我没有正确执行 base64 编码。 我究竟做错了什么?

buf = io.BytesIO()
plt.savefig(buf, format='png') # an image generated by a plotting library
plt.close(f)
# This produces a valid PNG image
file_path = os.path.join(module_dir, 'image1.png')
buf.seek(0)
buf_bytes = buf.read()
with open(file_path, 'wb') as output:
    output.write(buf_bytes)
# This is a valid base64 encoding of a small image, from Wikipedia
red_dot = "iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO9TXL0Y4OHwAAAABJRU5ErkJggg=="

# This works, i.e. the page displays a tiny red dot
return render(request, 'graph.html', {'graph1b64': red_dot})
# This does not work; the page displays the image alternate text
#return render(request, 'graph.html', {'graph1b64': base64.b64encode(buf_bytes)})
# This probably means I am not doing the base64 encoding correctly

# This is what is in the 'graph.html' template
#<div class="graph1">
#     <img src="data:image/png;base64, {{ graph1b64 }}" alt="graph1 in base64" />
#</div>

red_dot是一个字符串,而 b64encode 返回一个字节 object。 它应该与{'graph1b64': base64.b64encode(buf_bytes).decode()}

暂无
暂无

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

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