生成图像 - >嵌入在数据uri烧瓶 [英] generate image -> embed in flask with a data uri
问题描述
这个要点非常接近我的目标,除非我想避免使用 url_for
(从而路由)。相反,我想只显示图像数据内联使用数据uri(
img src =data:image / png; base64,...
)
而不是发送输出作为一个图像与响应,采取输出并编码到base64:
从cStringIO导入urllib
导入StringIO
png_output = StringIO()
canvas.print_png(png_output)
data = png_output.getvalue()。encode('base64')
data_url ='data:image / png; base64,{}'。 n')))
这将画布写入内存文件,并将生成的PNG然后将数据编码为base64并插入到数据URL中。
I am working on a Flask app which generates a dynamic plot and displays it through a jinja template. I would like to use the template to call a function in the Flask app which returns png data, and then embed the response in a data uri.
This gist is very close to my goal, except I would like to avoid using url_for
(and thus routes). Instead, I would like to just display the image data inline using a data uri (img src="data:image/png;base64,...
)
Instead of sending the output back as an image with a response, take the output and encode it to base64:
import urllib
from cStringIO import StringIO
png_output = StringIO()
canvas.print_png(png_output)
data = png_output.getvalue().encode('base64')
data_url = 'data:image/png;base64,{}'.format(urllib.quote(data.rstrip('\n')))
This has the canvas write to an in-memory file, and the resulting PNG data is then encoded to base64 and interpolated in a data URL.
这篇关于生成图像 - >嵌入在数据uri烧瓶的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!