簡體   English   中英

如何根據Django中的表單輸入向用戶顯示生成的圖像?

[英]How to display generated image to user based on form input in Django?

我目前正在使用對象的屬性通過 matplotlib 生成圖像,並且能夠創建一個在 HttpResponse 中顯示所述圖像的視圖。 我使用以下代碼段來做到這一點: http : //wiki.scipy.org/Cookbook/Matplotlib/Django 當我導航到 domain.com/objectID.png 時,我還配置了我的 URL 以成功生成和顯示圖像

現在我想創建一個表單,其輸入將用於從 matplotlib 生成圖像。 然后我想在表單的同一頁面上向用戶顯示這個生成的圖像。

我應該如何將表單的輸入提供給我的 matplotlib 圖像生成器,然后將生成的圖像顯示給用戶?

非常感謝您的幫助。

此致

編輯 1:我正在尋找解決方案,我相信我會在我的模板中顯示如下圖像。 雖然不確定如何提供變量 'img':

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

假設您要在用戶輸入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 ...

您將需要向服務器發出AJAX請求,以通過javascript提供一些網址(可能借助jQuery之類的庫)。 該請求將傳遞表格中的數據,並返回指向相應圖像的鏈接。

我的答案幾乎與接受的答案相同,但幾乎沒有工作變化。

視圖.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);
     }
   }
  )

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM