Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Render image without saving

Tags:

python

django

I want to get an image from user, work with it at beckend and render result back to user. Is it possible to do without saving image on disk?

my view:

class InputImageForm(forms.Form):
    image = forms.ImageField()


def get_image(request):
    if request.method == 'POST':
        form = InputImageForm(request.POST, request.FILES)
        if form.is_valid():
            image = request.FILES['image']
            #some actions with image
            return render_to_response('results.html', {'image': image})
        else:
           form = InputImageForm()
    else:
        raise Http404

In template, tag {{ image }} returns a name of file.

like image 776
Harkonnen Avatar asked Dec 25 '22 08:12

Harkonnen


2 Answers

The problem is that returning a page to the user would normally involve two requests: one for the HTML page, and one for the image itself as referenced by an img tag in that HTML. But as you say, without storing it anywhere in the meantime, the image would be lost.

There is an alternative: you can use a data uri to include the actual data for the image inline in the html. That means you won't have to persist it across requests, as everything will be returned at one. Data uris are supported in most browsers, including ie8+.

You can format the data like this, for example:

from base64 import b64encode

encoded = b64encode(img_data)
mime = "image/jpeg"
uri = "data:%s;base64,%s" % (mime, encoded)

And use it directly in the template:

<img src="{{ uri }}">
like image 191
Daniel Roseman Avatar answered Dec 31 '22 14:12

Daniel Roseman


If your form is Model Form .then jus try the below code.

from django.core.files import File
from django.core.files.temp import NamedTemporaryFile

class InputImageForm(forms.Form):
    image = forms.ImageField()
    class Meta:
       model = YourModel



def get_image(request):
    if request.method == 'POST':
        form = InputImageForm(request.POST, request.FILES)
        if form.is_valid():
            image = request.FILES['image']
            save_image_from_url(form,image)

        else:
           form = InputImageForm()
    else:
        raise Http404



def save_image_from_url(model, img):
    r = request.FILES['image']

    img_temp = NamedTemporaryFile(delete=True)
    img_temp.write(r.content)
    img_temp.flush()

    i = model.image.save("image.jpg", File(img_temp), save=True)
    return HttpResponse(i.read(), mimetype="YOUR MIME TYPE")
like image 22
Varnan K Avatar answered Dec 31 '22 14:12

Varnan K