【问题标题】:How to display generated image to user based on form input in Django?如何根据 Django 中的表单输入向用户显示生成的图像?
【发布时间】:2014-03-30 04:27:03
【问题描述】:

我目前正在使用对象的属性通过 matplotlib 生成图像,并且能够创建在 HttpResponse 中显示所述图像的视图。我使用以下 sn-p 来执行此操作: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


    【解决方案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 ...
    

    【讨论】:

    • 精彩的回复,非常感谢。如果您能引导我了解 JavaScript 函数,以便我完全理解发生了什么,我将不胜感激。
    • 所有的JS代码其实基本上都是为了访问jQuery和jQuery Form Plugin的API。因此,您不必真正担心它,因为处理表单的所有代码都已经编写在该插件中。你只需要写一些代码来访问他们的 API,我就是这么做的。阅读本文档:malsup.com/jquery/form/#getting-started
    • 在开始工作后接受了答案。非常感谢您的帮助!作为对未来读者的附注,我认为应该将表单 ID 从“#GenImgForm”固定为“GenImgForm”。
    • 谢谢。我很高兴它有帮助。感谢您在表单的id 中指出该错误。我现在已经修好了。
    【解决方案2】:

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

    【讨论】:

      【解决方案3】:

      我的答案与接受的答案几乎相同,但工作更改很少。

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

      【讨论】:

        猜你喜欢
        • 2019-08-08
        • 1970-01-01
        • 1970-01-01
        • 2014-05-15
        • 2012-08-17
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-06-11
        相关资源
        最近更新 更多