首页 > 解决方案 > 如何使用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”模板?

标签: pythonflask

解决方案


编辑:

如果您在文件夹中有图像,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 %}

编辑:

如果您要合并所有图像以创建单个图像,那么您将需要类似pillowopencv转换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那么它可能需要枕头来编辑图像并将文本放在图像上。
或者你将不得不学习CSSHTML.

<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 %}

推荐阅读