Amogh Kulkarni
Amogh Kulkarni

Reputation: 153

How to serve an image in Django using jquery

I am trying to update a div element in my html page with a png image which gets returned from the Django server.

In my client-side script where I send an ajax POST request on a button click, I have -

    $('#mybtn').click(function (event) {
        event.preventDefault();
        $.ajax({
            url: "/analysis",
            type: "POST",
            data: { 'data': $("#analysis_list").val(), csrfmiddlewaretoken: document.getElementsByName('csrfmiddlewaretoken')[0].value },
            success: function (response) {
                $('#imagediv').html('<img src=' + response + ' />');
            },
        });
    });

In my views.py, I have -

def analysis(request):
    dataFromClient = dict(request.POST)['data'][0]
    pathToImg = testAnalytics(dataFromClient)
    img = Image.open(pathToImg)
    response = HttpResponse(content_type="image/png")
    img.save(response, "PNG")
    return response

Where testAnalytics method generates the image to be displayed according to the data sent by client and returns the path to it. Image is imported from PIL.

I am facing problem with rendering the image at client-side javascript. When I assign response to src attribute of the <img> tag, I see raw image data on the browser instead of the image (as discussed in here - How to update a div with an image in Django?). I am not sure where I am going wrong.

I have also tried base64 encoding on the response as follows (but not sure whether I have implemented correctly) -

success: function (response) {
                $('#imagediv').html('<img alt="Embedded Image" src="data:image/png;base64,' + response + '" />');
            }

I have referred to following links to get upto this point -
Django: How to render image with a template
Serve a dynamically generated image with Django

I am fairly new to web-programming as well as Django. Any insights regarding the problem will be really helpful. Thanks in advance.

Upvotes: 5

Views: 2454

Answers (2)

M.javid
M.javid

Reputation: 6647

If you want set image by content of any HTML tags you must apply data:{type};{encode-format} before image content and set background url in CSS, similar below:

html-element{
   background:url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAAEklEQVQImWNgIAD+QzFuAeIAAPVzA/0vfQ+9AAAAAElFTkSuQmCC) repeat;
}

Or set this by src attribute of img tag:

<img src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAAEklEQVQImWNgIAD+QzFuAeIAAPVzA/0vfQ+9AAAAAElFTkSuQmCC">

for example if you generate a new pattern in www.patternify.com site, you can copy and use base64 content from Base64 Code field.

Upvotes: 0

statBeginner
statBeginner

Reputation: 849

Try encoding the image using base64 before you send it.

import base64
#rest of your code 
with open("pathToImage.png", "rb") as image_file:
    encoded_string = base64.b64encode(image_file.read())

Then

success: function(response){
            $('#imagediv').html('<img src="data:image/png;base64,' + response + '" />');

Upvotes: 3

Related Questions