Python3 image base64不保存为html img标记

Python3 image base64不保存为html img标记,python,html,image,base64,Python,Html,Image,Base64,我想创建一个图像(不保存到磁盘),并在浏览器中显示它。我知道我必须创建一个base64映像,但我不知道如何创建它 你能帮我吗 这是我的密码: 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&

我想创建一个图像(不保存到磁盘),并在浏览器中显示它。我知道我必须创建一个base64映像,但我不知道如何创建它

你能帮我吗

这是我的密码:

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)
从PIL导入图像,ImageDraw
导入base64
im=Image.new('RGBA',(200100),color='black')
data_uri=#缺少如何将图像转换为base64?
html=“”
html+=''.format(数据uri)
html+=''
打印(html)

您需要将图像转换为适当的格式(本例中为PNG)作为缓冲区,并在缓冲区之后对其进行编码

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) 
从PIL导入图像,ImageDraw
导入base64
输入io
im=Image.new('RGBA',(200100),color='black')
buffer=io.BytesIO()
im.save(缓冲区,format='PNG')
buffer.seek(0)
data_uri=base64.b64encode(buffer.read()).decode('ascii'))
html=“”
html+=''.format(数据uri)
html+=''
打印(html)