python - 如何使用flask render_template API为模板文件夹中的HTML模板返回多个图像?
问题描述
我想从本地文件路径中读取一些本地图像(.jpg),然后使用flask和python3在网页(127.0.0.1:8000)上显示这些图像。我已经通过使用在网页上显示单个图像以下代码:
from flask import Flask,render_template
app = Flask(__name__)
def return_img_stream(img_local_path):
import base64
img_stream = ''
with open(img_local_path, 'rb') as img_f:
img_stream = img_f.read()
img_stream = base64.b64encode(img_stream).decode()
return img_stream
@app.route('/')
def hello_world():
img_path = 'D:\\1111\\1.jpg'
img_stream = return_img_stream(img_path)
return render_template('index.html',img_stream=img_stream)
if __name__ == '__main__':
app.run(debug=True,host='127.0.0.1',port=8080)
我应该如何修改 return_img_stream 和 hello_world 函数以使用烧瓶读取多图像流并将其发送到“index.html”模板?
解决方案
编辑:
如果您在文件夹中有图像,static
那么您可以只发送带有文件名的列表并for
在模板中使用 -loop 来生成标签,例如<img src="/static/1.jpg">
@app.route('/')
def hello_world():
#filenames = os.listdir('static')
filenames = ['1.jpg', '2.jpg']
return render_template('index.html', filenames=filenames)
模板
{% for name in filenames %}
<img src="/static/{{ name }}">
{% endfor %}
如果你需要使用,base64
那么你必须for
在 Flask 中使用 -loop
@app.route('/')
def hello_world():
#filenames = os.listdir('D:\\1111')
#filenames = [os.path.join('D:\\1111', name) for name in filenames]
filenames = ['D:\\1111\\1.jpg', 'D:\\1111\\2.jpg']
images = []
for img_path in filenames:
img_stream = return_img_stream(img_path)
images.append(img_stream)
return render_template('index.html', images=images)
模板
{% for img in images %}
<img src="data:image/jpeg;base64, {{ img }}">
{% endfor %}
编辑:
如果您要合并所有图像以创建单个图像,那么您将需要类似pillow
或opencv
转换jpg
为原始图像的模块,合并它们,将其转换回单个jpg
。
编辑:
如果您想添加带有一些文本的图像(即带有文件名),那么您必须创建带有对的列表(image, text)
并{% for img, txt in images %}
使用{{ txt }}
@app.route('/')
def hello_world():
#filenames = os.listdir('D:\\1111')
#filenames = [os.path.join('D:\\1111', name) for name in filenames]
filenames = ['D:\\1111\\1.jpg', 'D:\\1111\\2.jpg']
images = []
for img_path in filenames:
img_stream = return_img_stream(img_path)
images.append( [img_stream, img_path ])
return render_template('index.html', images=images)
模板
{% for img, txt in images %}
filename: {{ txt }}<br/>
<img src="data:image/jpeg;base64, {{ img }}">
{% endfor %}
但如果你的意思是text on image
那么它可能需要枕头来编辑图像并将文本放在图像上。
或者你将不得不学习CSS
在HTML
.
<style>
div.image { ... }
div.image span { ... }
</style>
{% for img, txt in images %}
<div class="image">
<span>filename: {{ txt }}</span>
<img src="data:image/jpeg;base64, {{ img }}">
<div>
{% endfor %}
推荐阅读
- javascript - 验证javascript中的输入值
- git - 不能先推送到基于 docker 的 gitlab 服务器
- html - 填充 Font-awesome 图标的透明度
- javascript - 如何在 Nest.js 中查询多个 @ManyToMany 中的数据
- javascript - 将数据转换为具有多级标题的 HTML 数据透视表
- java - Eclipse 的代码搜索功能如何工作?
- git - Git - 如何“软”合并?
- mysql - 尝试创建表时出现错误,我不知道为什么
- c - 添加两个 char 数组的值
- windows-subsystem-for-linux - 在 Windows 上使用多个 linux 子系统更改 bash.exe