我有一些 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>