FabioDev
FabioDev

Reputation: 754

How render binary image in javascript

My flask python app return an image as a response from a POST request:

def upload_file():
    if request.method == 'POST':
        return send_file('1.png', mimetype='image/png')

Then I want to use javascript and jquery ajax to do the request, and the response is:

success: function(img_response) {
            console.log(img_response);
}

�PNG ��� IHDR����������?1�� �IDATx����nIv��vdU�Ѓ�ۀm6f`�����?���W3�1��%6Y��ER�xh�Pb��]�R�DfeFF�qo��_����O�4�]J$��.�%E�%E�ɲ$)...

How can I render this type of file in browser? Maybe is better decode the image in base64 in flask, but how can I do it?

Upvotes: 3

Views: 4972

Answers (1)

Gustavo Topete
Gustavo Topete

Reputation: 1296

You should take a look here for encoding a binary to base64 with python. Once you got it, send the string to your app (frontend) as a response, then you can add something like:

<img id="myImgTag" src="data:image/png;base64, YOUR_BASE64_STRING_FROM_RESPONSE"></img>

You can add it with javascript with something like:

let img = document.getElementById('myImgTag').setAttribute('src','data:image/png;base64, YOUR_BASE64_STRING_FROM_RESPONSE')

====EDIT===

To read the file and encode it to base64 do the following:

import base64
...
myImage = open('your_file_name','rb')
myBase64File = base64.b64encode(myImage.read())

Then just use Flask to send 'myBase64File' var as you want (might be inside a JSON, as plain text, etc.)

Upvotes: 1

Related Questions