显示上传/选择的图像,而不将其保存在Django

时间:2016-11-09 09:03:12

标签: python django

我希望将用户上传的图像存储在views.py中的变量中(并在其上应用一些opencv操作),然后显示结果图像。 我不想将图像存储在数据库中。所以,我不认为模型是实现这一点所必需的。怎么进一步?以下是index.htmlviews.py。对不起,如果有任何编码错误,我是Django的新手。

的index.html

<form method="POST" enctype="multipart/form-data">{% csrf_token %}
    <div class="file-field input-field left">
        <div class="btn black-text waves-effect waves-dark" style="background-color: #F5DF73">
            <div>Upload</div>
            <input type="file" name = "input_image" onchange="readURL(this);">
        </div>
        <div class="file-path-wrapper">
           {#<input class="file-path validate" type="text">#}
        </div>
    </div>
    {{ image }}
</form>

views.py

def upload_pic(request):

    if request.method == 'POST':
        form = ImageUploadForm(request.POST, request.FILES)
        image = form.cleaned_data['image']

    return render(request, 'html/index.html', {"image": image})

urls.py

urlpatterns = [
    url(r'^$', views.index),
]

3 个答案:

答案 0 :(得分:3)

试试这个

form = ImageUploadForm(request.POST)
image = form.cleaned_data['image']
b64_img = base64.b64encode(image.file.read())

return render(request, 'html/index.html', {"image": b64_img})

在html中

<img src="data:image/png;base64,{{image}}">

答案 1 :(得分:2)

我是这样做的:

<强> views.py

def process_image(request):

    # inputImage is the name attribute of the <input> tag in the html
    inImg = request.FILES["inputImage"].read()

    encoded = b64encode(inImg)
    mime = "image/jpg"
    mime = mime + ";" if mime else ";"
    input_image = "data:%sbase64,%s" % (mime, encoded)        

    return render(request, "../templates/index.html", {{ "input_image": input }})

<强>的index.html:

<input src = '{{ input_image }}' name = 'inputImage' type="text">

答案 2 :(得分:0)

对我来说,这很管用

import io
import base64
data = io.BytesIO()
image.save(data, "JPEG")
encoded_img_data = base64.b64encode(data.getvalue())
out=encoded_img_data.decode('utf-8')

views.py 函数

return render(request, 'html/index.html', {"image": out})

index.html

<img src="data:image/png;base64,{{image}}">