如何根据Django输入的表单向用户显示生成的图像?

问题描述 投票:2回答:3

我目前正在使用对象的属性通过matplotlib生成图像,并且能够创建在HttpResponse中显示该图像的视图。我使用以下代码片段进行了此操作: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 %}
javascript jquery python django matplotlib
3个回答
1
投票

假设您要在用户输入xy坐标后生成简单的图形/图像。

需求:

  1. jQuery
  2. jQuery Form Plugin

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>

views.py:

现在,在views中,您将必须采用这种方法:

  1. 使用matplotlib生成图像。
  2. 将其另存为StringIO对象。
  3. StringIO对象编码为base64
  4. 将其发送回客户端。

看看this question

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 ...

0
投票

您需要向服务器发出AJAX请求,以通过javascript提供一些网址(可能借助jQuery之类的库)。该请求将传递表单中的数据,并返回指向相应图像的链接。


0
投票

我的答案几乎与公认的答案相同,几乎没有任何工作上的改变。

views.py:

from matplotlib import pyplot as plt
import io
plt.plot([1, 2, 3, 4])
plt.ylabel('some numbers')
sio = io.BytesIO()
plt.savefig(sio, format="png")
encoded_img = base64.b64encode(sio.getvalue())
return HttpResponse(encoded_img)

html:

<img id="plt" src=""></img>

jQuery ajax代码:

  $.ajax(
   {
     headers: {"X-CSRFToken":token},
     type: "GET",
     url: "ajax/show_hcPlot",
     success: function(response){

       $("#plt").attr('src',"data:image/png;base64, " + response);
     }
   }
  )
© www.soinside.com 2019 - 2024. All rights reserved.