我正在使用这段代码从 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 文件,那么您可以在没有 cv2
、PIL
和 io
的情况下执行相同的操作
data = open('image.png', 'rb').read()
image = base64.b64encode(data).decode()
关于python - 在python中渲染图像以在html中显示,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59797457/