【问题标题】:Python 3 image base64 without saving into html img tagPython 3图像base64而不保存到html img标签
【发布时间】:2018-10-31 05:37:48
【问题描述】:

我想创建一个图像(不将其保存到磁盘),并在浏览器中显示它。据我所知,我必须创建一个 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)

【问题讨论】:

    标签: python html image base64


    【解决方案1】:

    您需要将图像转换为正确的格式(在这种情况下为 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) 
    

    【讨论】:

      猜你喜欢
      • 2021-05-25
      • 1970-01-01
      • 1970-01-01
      • 2014-09-29
      • 2023-03-23
      • 2016-03-11
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多