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

3 投票
3 回答
1892 浏览
提问于 2025-04-18 00:31

我现在正在用matplotlib生成一张图片,这张图片是根据一个对象的属性来创建的。我已经能成功地把这张图片显示在HttpResponse里。为了做到这一点,我用了下面的代码片段:http://wiki.scipy.org/Cookbook/Matplotlib/Django。我还配置了我的网址,这样当我访问domain.com/objectID.png时,可以成功生成并显示这张图片。

现在我想创建一个表单,用户在这个表单里输入的信息将用来生成一张matplotlib的图片。然后我想把生成的图片在同一个表单页面上显示给用户。

我应该怎么把表单里的输入传给我的matplotlib图片生成器,然后再把生成的图片显示给用户呢?

非常感谢你的帮助。

祝好

编辑 1:
我在寻找解决方案,我觉得我可以在我的模板里这样显示图片。不过我不太确定怎么把变量'img'传进去:

{% if img %} <img border="0" alt="My Generated Image" src="{{ img }}" /> {% endif %}

3 个回答

0

你需要用JavaScript向服务器发送一个AJAX请求,这样才能通过某个网址获取数据(可能还需要用到像jQuery这样的库来帮助你)。这个请求会把表单里的数据发送过去,然后服务器会返回一个合适的图片链接。

1

我的回答和被接受的答案差不多,只是做了一些有效的修改。

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);
     }
   }
  )
3

假设你想在用户输入了 xy 坐标后,生成一个简单的图形或图片。

需求:

  1. jQuery
  2. jQuery 表单插件

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. 把它发送回客户端。

可以看看 这个问题

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

撰写回答