How to convert file stream to data URI in Python?

I have an image file stream in Python:

\x89PNG\r\n\x1a\n\x00\x00\x00\rIHDR\x00\x00\x04\x87...

How do I convert this to a data URI ?

'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAU...'
+3
source share
1 answer

Encode it in base64, then remove the newlines.

>>> '\x89PNG\r\n\x1a\n\x00\x00\x00\rIHDR\x00\x00\x04\x87...'.encode('base64').replace('\n', '')
'iVBORw0KGgoAAAANSUhEUgAABI....'
+6
source

All Articles