Sometimes, we want to display image on a HTML page with Python Flask.
In this article, we’ll look at how to display image on a HTML page with Python Flask.
How to display image on a HTML page with Python Flask?
To display image on a HTML page with Python Flask, we can pass the image path to the template from the view.
For instance, we write
from flask import Flask, render_template
import os
PEOPLE_FOLDER = os.path.join('static', 'people_photo')
app = Flask(__name__)
app.config['UPLOAD_FOLDER'] = PEOPLE_FOLDER
@app.route('/')
@app.route('/index')
def show_index():
full_filename = os.path.join(app.config['UPLOAD_FOLDER'], 'image.jpg')
return render_template("index.html", user_image = full_filename)
to get the image path with
full_filename = os.path.join(app.config['UPLOAD_FOLDER'], 'image.jpg')
Then we call render_template
with the template file name, and the user_image
argument set to the image path.
Next, we render the image in the index.html template by writing
<!DOCTYPE html>
<html>
<head>
<title>Index</title>
</head>
<body>
<img src="{{ user_image }}" alt="User Image">
</body>
</html>
to interpolate the user_image
in the template.
Conclusion
To display image on a HTML page with Python Flask, we can pass the image path to the template from the view.