Skip to main content
 首页 » 编程设计

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

2025年05月04日21youxin

我目前正在使用对象的属性通过 matplotlib 生成图像,并且能够创建一个在 HttpResponse 中显示所述图像的 View 。我使用以下代码片段来执行此操作: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 和 y 坐标后生成一个简单的图形/图像。

要求:

  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 :

现在,在您的 View 中,您必须遵循以下方法:

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