【问题标题】:python: Given a BytesIO buffer, generate img tag in html?python: 给定一个 BytesIO 缓冲区,在 html 中生成 img 标签?
【发布时间】:2013-07-07 06:43:03
【问题描述】:

是否可以从 BytesIO 缓冲区生成 html 中的功能图像标签?我想按照这些思路做一些事情:

import matplotlib
matplotlib.use('Agg') 
import pylab
import Image
import io

temp_data = {'x':[1,2,3],'y':[2,4,5]}
pylab.plot(temp_data['x'], temp_data['y'])

img_buffer = io.BytesIO()
pylab.savefig(img_buffer, format = 'png')
img_buffer.seek(0)

img_tag = "<img src='data:image/png;base64,'" + img_buffer.getvalue() + "</img>"

可能需要以某种方式重新格式化缓冲区的值,或者更改“src”数据的内容。谢谢。

【问题讨论】:

    标签: python html image buffer


    【解决方案1】:

    Python2

    在上面代码的末尾,执行此操作

    import base64
    img_tag = "<img src='data:image/png;base64," + base64.b64encode(img_buffer.getvalue()) + "'/>"
    

    Python3

    为了在 python3 中工作,您需要使用 str.decode 方法将 base64.b64encode 生成的字节变量解码为字符串,如下所示

    import base64
    str_equivalent_image = base64.b64encode(img_buffer.getvalue()).decode()
    img_tag = "<img src='data:image/png;base64," + str_equivalent_image + "'/>"
    

    【讨论】:

      【解决方案2】:

      如果您正在使用Flask,那么您可以返回图像的UTF-8 格式并使用它。

      figfile = BytesIO()
      plt.savefig(figfile, format='png')
      
      plt.clf() # this will clear the image
      
      figfile.seek(0)
      figdata_png = base64.b64encode(figfile.getvalue())
      return figdata_png.decode('UTF-8')
      

      记得在&lt;img/&gt; 标签中提及它。这是在Flask中实现的。

      【讨论】:

        猜你喜欢
        • 2012-06-07
        • 2010-09-25
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-01-02
        • 1970-01-01
        • 2021-02-06
        相关资源
        最近更新 更多