【问题标题】:Rendering Image in python to display in html在python中渲染图像以在html中显示
【发布时间】:2020-05-04 22:30:39
【问题描述】:

我正在使用此代码块从 python 发送图像以显示在 HTML 中。

x = cv2.imread(file)
x = cv2.cvtColor(x, cv2.COLOR_RGB2BGR)
img = io.BytesIO()
x = Image.fromarray(x, 'RGB')
x.save(img, 'PNG')
img.seek(0)
array.append(base64.b64encode(img.getvalue()))
k= k+1
id.append(k)

render_template('html_page.html', data=zip(array,id))

在 HTML 页面中显示的代码:

{%for i,j in data%}
          <img for="id{{i}}" style = "float:left; width: 180px;" src="data:image/PNG;base64,{{ i }}" alt="display_Image">
{% endfor %}

图片没有显示在浏览器中。

谁能指出我做错了什么?尝试用 Python 学习图像处理。

在调试时,我可以看到图像在 python 函数中成功加载,但没有显示在 HTML 页面中。

【问题讨论】:

    标签: python html image


    【解决方案1】:

    问题是因为base64 给出了bytes,而后来的模板在将bytes 转换为string 时添加了前缀b。您必须手动将decode() bytes 改为string

    base64.b64encode(img_io.getvalue()).decode()
    

    顺便说一句:如果您有 PNG 文件,那么您可以在没有 cv2PILio 的情况下执行相同操作

    data = open('image.png', 'rb').read()
    image = base64.b64encode(data).decode()
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-12-09
      • 1970-01-01
      • 1970-01-01
      • 2011-03-25
      • 1970-01-01
      • 2011-09-28
      相关资源
      最近更新 更多