生成图像 - >嵌入在数据uri烧瓶 [英] generate image -> embed in flask with a data uri

查看:112
本文介绍了生成图像 - >嵌入在数据uri烧瓶的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在开发一个Flask应用程序,它会生成一个动态图并通过jinja模板显示出来。我想用这个模板来调用Flask应用程序中的一个返回png数据的函数,然后将响应嵌入到一个数据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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆