Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I convert a file stream to a data URI in Python?

I have a file stream of an image 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...'
like image 692
Matt Norris Avatar asked Dec 09 '25 20:12

Matt Norris


1 Answers

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....'
like image 66
Ignacio Vazquez-Abrams Avatar answered Dec 12 '25 11:12

Ignacio Vazquez-Abrams



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!