我目前正在使用对象的属性通过 matplotlib 生成图像,并且能够创建一个在 HttpResponse 中显示所述图像的视图。我使用以下代码片段来执行此操作:http://wiki.scipy.org/Cookbook/Matplotlib/Django http://wiki.scipy.org/Cookbook/Matplotlib/Django。我还配置了 URL,以便在导航到 domain.com/objectID.png 时成功生成和显示图像
现在我想创建一个表单,其输入将用于从 matplotlib 生成图像。然后我想在表单的同一页面上向用户显示生成的图像。
我应该如何将表单的输入提供给 matplotlib 图像生成器,然后将生成的图像显示回用户?
非常感谢您的帮助。
此致
编辑1:
我正在寻找解决方案,我相信我会在模板中显示如下图像。但不确定如何提供变量“img”:
{% if img %} <img border="0" alt="My Generated Image" src="{{ img }}" /> {% endif %}
假设您想在用户输入后生成一个简单的图形/图像x
and y
坐标。
要求:
- jQuery http://jquery.com/
- jQuery 表单插件 http://malsup.com/jquery/form/#download
HTML :
<form method="POST" action="/generate-image/" id="GenImgForm">
<input type="text" name="x-coordinate" />
<input type="text" name="y-coordinate" />
</form>
<!-- Make an empty div where the returned image will be shown -->
<div id="ShowImage"></div>
<script type="text/javascript" src="/static/path/to/jquery.js"></script>
<script type="text/javascript" src="/static/path/to/jquery.form.js"></script>
<script type="text/javascript">
$(document).ready(function() {
var options = {
target: '#ShowImage',
};
$("#GenImgForm").ajaxForm(options);
return false;
});
</script>
视图.py:
现在,在你的views
,你必须遵循这种方法:
- 使用生成图像
matplotlib
.
- 将其另存为
StringIO
object.
- 编码
StringIO
反对base64
.
- 将其发送回客户端。
看一眼这个问题 https://stackoverflow.com/questions/14824522/dynamically-serving-a-matplotlib-image-to-the-web-using-python.
import cStringIO # use import io in Python 3x
# import base64 Use this in Python 3x
def generate_image(request):
if request.method == 'POST':
x_coord = request.POST['x-coordinate']
y_coord = request.POST['y-coordinate']
# generate a matplotlib image, (I don't know how to do that)
sio = cStringIO.StringIO() # use io.StringIO() in Python 3x
pyplot.savefig(sio, format="PNG")
encoded_img = sio.getvalue().encode('Base64') # On Python 3x, use base64.b64encode(sio.getvalue())
return HttpResponse('<img src="data:image/png;base64,%s" />' %encoded_img)
else:
# Do something ...
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)