Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 734
FabioDev Avatar asked May 16 '26 19:05

FabioDev


1 Answers

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

like image 139
Gustavo Topete Avatar answered May 19 '26 09:05

Gustavo Topete



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!