python - 在python中渲染图像以在html中显示

标签 python html image

我正在使用这段代码从 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 页面中显示。

最佳答案

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

base64.b64encode(img_io.getvalue()).decode()
<小时/>

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

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

关于python - 在python中渲染图像以在html中显示,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59797457/

相关文章:

python - 如何在继承的 CrawlSpider 中重用基于 scrapy Spider 的蜘蛛的解析方法?

python - 2 网络摄像头饲料不工作 opencv

html - 网格属性不适用于网格容器内的元素

android - 可绘制在某些设备上模糊

javascript - 如何使用JQuery获取真实图像高度?

python - 删除时区(+01 :00) from DateTime

python - Python 中缺少关键字参数

html - 如何获得没有链接的文本?

html - 我可以在关键帧内的元素上指定 ID 以使用 sass 减少 CSS 吗?

css - 调整窗口大小时 HTML/CSS 图像更改位置