How to use image in Django using jquery

I am trying to update a div element in my html page using a png image that is returned from a Django server.

In my client side script, where I send ajax POST request when a button is clicked, 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 the testAnalytics method generates an image that will be displayed in accordance with the data sent by the client, and returns the path to it. Image imported from PIL .

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

I also tried base64 encoding in the answer as follows (but not sure if I implemented correctly) -

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

I mentioned the following links to go to this question -
Django: how to make an image using a template
Serve dynamically generated image with Django

I am new to web programming as well as to Django. Any information about the problem would be really helpful. Thanks in advance.

+5
source share
2 answers

Try encoding the image with base64 before sending 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 + '" />'); 
+2
source

If you want to set the image according to the content of any HTML tags, you must apply data:{type};{encode-format} in front of the image content and set the background url in CSS, as shown below:

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

Or set this src attribute of the img tag:

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

for example, if you create a new template at www.patternify.com , you can copy and use base64 content with Base64 Code .

0
source

All Articles