Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create an HTML img tag string with base64 encoding from bytes in Python?

I am using Python 3.6 and I have an image as bytes:

img = b'\xff\xd8\xff\xe0\x00\x10JFIF\x00'

I need to convert the bytes into a string without encoding so it looks like:

raw_img = '\xff\xd8\xff\xe0\x00\x10JFIF\x00'

The goal is to incorporate this into an html image tag:

"<img src=" + "'data:image/png;base64," + base64.b64encode(raw_img) + "' />"
like image 908
slaw Avatar asked Jul 21 '26 17:07

slaw


2 Answers

img.decode("utf-8")

You can decode the variable with the above. Then convert it to base64.

"<img src='data:image/png;base64,{}'/>".format( base64.b64encode(img.decode("utf-8")) )

UPDATED:

What you really want is this:

raw_img = repr(img)
"<img src='data:image/png;base64,{}'/>".format( base64.b64encode(raw_img) )
like image 77
eatmeimadanish Avatar answered Jul 23 '26 05:07

eatmeimadanish


I've solved it (2022 - bit late to the party...) If you try img_raw.decode() you get the UnicodeDecodeError: 'utf-8' codec can't decode byte 0xff in position 0: invalid start byte error

But if you leave img_raw as a binary string and pass it into b64encode and then decode it, it doesn't have the UnicodeDecodeError, and you can pass it in as a data string to your image tag.

base64.b64encode(raw_image).decode()

like image 44
lizj Avatar answered Jul 23 '26 05:07

lizj



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!