hulkinBrain
hulkinBrain

Reputation: 746

Display uploaded/chosen image without saving it in database in Django

I'd like to store the image which the user uploads, in a variable within views.py (and apply some opencv operations on it) and then display the resultant image. I don't want to store the image in a database. So, i don't think models are necessary for implementing this. How to proceed further? Following are the index.html and views.py. Sorry if any coding mistakes are there, i'm new to 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),
]

Upvotes: 4

Views: 4149

Answers (3)

Talha Anwar
Talha Anwar

Reputation: 2949

For me, this works

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 function

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

index.html

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

Upvotes: 0

hulkinBrain
hulkinBrain

Reputation: 746

I did it by doing this:

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

Upvotes: 2

itzMEonTV
itzMEonTV

Reputation: 20359

Try this

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

In html

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

Upvotes: 2

Related Questions