[英]Encode PNG image in base64 in Python
I have some Python code that generates a dynamic image in PNG format.我有一些 Python 代码可以生成 PNG 格式的动态图像。 This works correctly, because I can save the bytes to disk and get a valid PNG image.这可以正常工作,因为我可以将字节保存到磁盘并获得有效的 PNG 图像。 Then I try to encode the bytes in base64 and pass them to an HTML template (in a Django website) to get the image rendered.然后我尝试对 base64 中的字节进行编码,并将它们传递给 HTML 模板(在 Django 网站中)以渲染图像。 This can be done, because I can get it to work if I pass a base64 string that is known to be correct.这是可以做到的,因为如果我传递一个已知正确的 base64 字符串,我就可以让它工作。 But it does not work with my string, probably because I am not doing the base64 encoding correctly.但它不适用于我的字符串,可能是因为我没有正确执行 base64 编码。 What am I doing wrong?我究竟做错了什么?
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
is a string whereas b64encode returns a bytes object. red_dot
是一个字符串,而 b64encode 返回一个字节 object。 It should work with {'graph1b64': base64.b64encode(buf_bytes).decode()}
.它应该与{'graph1b64': base64.b64encode(buf_bytes).decode()}
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.