Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python 3 image base64 without saving into html img tag

I would like to create an image (without save it to the disk), and show it in a browser. As I know I have to create a base64 image, but I don't know how I can make it.

Can you help me?

Here is my code:

from PIL import Image, ImageDraw
import base64

im = Image.new('RGBA', (200, 100),  color = 'black')
data_uri = #missing how I can convert the image to base64 ?

html = '<html><head></head><body>'
html += '<img src="data:image/png;base64,{0}">'.format(data_uri)
html += '</body></html>'

print (html)
like image 993
Hack Avatar asked Dec 10 '22 06:12

Hack


1 Answers

You need to get image into proper format (PNG in this case) as buffer and encode buffer after.

from PIL import Image, ImageDraw
import base64
import io

im = Image.new('RGBA', (200, 100),  color = 'black')

buffer = io.BytesIO()
im.save(buffer, format='PNG')
buffer.seek(0)

data_uri = base64.b64encode(buffer.read()).decode('ascii')

html = '<html><head></head><body>'
html += '<img src="data:image/png;base64,{0}">'.format(data_uri)
html += '</body></html>'

print (html) 
like image 141
Stanislav Ivanov Avatar answered Dec 31 '22 23:12

Stanislav Ivanov