Search code examples
javascriptimageinnerhtmldata-conversion

Display image from a string of bytes


I received the bytes of the image from a server which passes the bytes through websockets. The received message looks like this:

b'\xff\xd8\xff\xe0\x00\x10JFIF\x00\x01\x01\x00\x00\x01\x00\x01\x00\x00\xff\xe1\x006Exif\x00\x00II*\x00\x08\x00\x00\x00\x01\x002\x01\x02\x00\x14\x00\x00\x00\x1a\x00\x00\x00\x00\x00\x00\x002007:09:12 11:56:03\x00\xff\xdb\x00C\x00\x06\x04\x05\x06\x05\x04\x06\x06\x05\x06\x07\x07\x06\x08\n\x10\n\n\t\t\n\x14\x0e\x0f\x0c\x10\x17\x14\x18\x18\x17\x14\x16\x16\x1a\x1d%\x1f\x1a\x1b#\x1c\x16\x16 , #&\')*)\x19\x1f-0-(0%()(\xff\xdb\x00C\x01\x07\x07\x07\n\x08\n\x13\n\n\x13(\x1a\x16\x1a((((((((((((((((((((((((((((((((((((((((((((((((((\xff\xc2\x00\x11\x08\x01\xe0\x02H\x03\x01"\x00\x02\x11\x01\x03\x11\x01\xff\xc4\x00\x1b\x00\x00\x02\x03\x01\x01\x01\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x04\x05\x02\x03\x06\x01\x00\x07\xff\xc4\x00\x19\x01\x00\x03\x01\x01\x01\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x01\x02\x03\x04\x05\xff\xda\x00\x0c\x03\x01\x00\x02\x10\

(This is just a piece of the message, obviously there are too many bytes to share them all here).

This info is stored in a variable called input and I want to display its values in an HTML image which id is "img". I tried the following code:

document.getElementById("img").src=input;

But then I realized that as I said earlier, input is a string.

Is there a way to display the image from the data I stored in input? Thank you in advance.


Solution

  • Did you ever tried this one?

    document.getElementById("img").src = "data:image/png;base64," + input;