I have a byte format jpeg that I get from python that looks like this b'\xff\xd8\xff\xe0\x00\x10JFIF\x00\x01\x01\...'
. How can I display that inside an HTML img
tag? Any help is appreciated. Thanks in advance.
CodePudding user response:
Encode the bytes to base64, then use the native HTML b64 format for your image:
from base64 import b64encode
bytez = b'\xff\xd8\xff\xe0\x00\x10JFIF\x00\x01\x01'
b64_encoded = b64encode(bytez).decode()
print(b64_encoded)
>>> '/9j/4AAQSkZJRgABAQ=='
and then:
<img src="data:image/jpg;base64, /9j/4AAQSkZJRgABAQ==" alt="Your image" />
CodePudding user response:
Simple answer: write it to a file and have the HTML refer to it.
b = b'\xff\xd8\xff\xe0\x00\x10JFIF\x00\x01\x01\...'
with open('image.jpg', 'wb') as f:
f.write(b)
In the HTML document:
<img src="image.jpg">
Hairier answer:
base64 encode it,
using data:image/jpeg;base64
.
CodePudding user response:
To display the byte format image inside an HTML img tag, you can use the data attribute of the img tag and set it to the base64-encoded version of the image data.
Here is an example of how you can do this in Python:
import base64
# Encode the image data in base64
image_data_base64 = base64.b64encode(image_data)
# Convert the base64-encoded data to a string
image_data_base64_string = image_data_base64.decode('utf-8')
# Create an HTML img tag with the base64-encoded image data as the value of
#the `src` attribute
html_img_tag = f'<img src="data:image/jpeg;base64,
{image_data_base64_string}">'
You can then use the html_img_tag variable in your HTML code to display the image. For example:
<html>
<body>
{html_img_tag}
</body>
</html>
Alternatively, you can also use the Python library Pillow to convert the image data to a PNG format and then save it to a file, which you can then reference in the img tag's src attribute like any other image file:
from PIL import Image
# Open the image data as a Pillow image
image = Image.open(io.BytesIO(image_data))
# Save the image to a file
image.save('image.png')
# Create an HTML img tag with the file path as the value of the `src` attribute
html_img_tag = '<img src="image.png">'