python - Python 3图像base64而不保存到html img标签
问题描述
我想创建一个图像(不将其保存到磁盘),并在浏览器中显示它。据我所知,我必须创建一个 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)
解决方案
您需要将图像转换为正确的格式(在这种情况下为 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)
推荐阅读
- html - 将#a 悬停到#one 样式,其中#one 是#b 的子元素,#b 是#a 的兄弟元素
- reactjs - 反应流类型错误
- angular - 动态样式表链接
- java - 用于数字浮动的正则表达式黄瓜小黄瓜
- python - 在我的 Mac 上用 Python 安装 BeautifulSoup 时,我遇到了这个问题。我已经更新了设置工具,问题依然存在
- html - 通过 Excel VBA 实现 IE11 自动化 - 表单
- angular - 手势处理 AgmMap 不起作用
- c# - Access Api 在浏览器上创建了谷歌电子表格
- javascript - 在 ionic 3 中导入依赖于 jQuery 的库
- c++ - 多个重载函数实例