How to display image from binary data that I am receiving from python?

Question:

I am using python to convert a image to binary. I am getting the output. But I cannot revert back the binary code to image display using data:image/jpeg;base64. Can anyone help?

Python code:
----------------
f = open("demo.jpg", 'rb')
file_content = f.read()
f.close()
print(file_content)

Now I am getting the binary data inside the variable "file_content" from the above code and using it in html.

Html


<!DOCTYPE html>
<html>
<head>
    <title></title>
</head>
<body>
<script type="text/javascript">
    function hexToBase64(str) {
    return btoa(String.fromCharCode.apply(null, str.replace(/r|n/g, "").replace(/([da-fA-F]{2}) ?/g, "0x$1 ").replace(/ +$/, "").split(" ")));
}

var img = new Image();
img.src = "data:image/jpeg;base64,"+hexToBase64(getBinary());
document.body.appendChild(img);

function getBinary() {
    return 'xxxxBinary dataxxxxxxxxx'
}




</body>

The error is showing as "Unexpected string". It is showing the error in the binary data. I think there is some misuse of single qoutes in the return type. But I cant understand how to wrap the binary data.

Answers:

Why don’t you encode the image to base64 on python side and in the webpage simply set the encoded data on the image src e.g. check following example

import base64

f = open('demo.jpg', 'rb')
img_encoded = base64.b64encode(f.read())
# img_encoded is the encoded image use that in the webpage
# i.e. no need to use hexToBase64()
Answered By: Zain Ul Abidin
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.