how to put a image in flask
To put an image in Flask, you can follow these steps:
First, make sure you have a folder in your Flask project where you can store your images. You can create a folder called "static" in the project root directory and place your images inside it.
In your Flask application file (usually named
app.py
ormain.py
), import theFlask
andrender_template
modules:
from flask import Flask, render_template
- Create a Flask application instance:
app = Flask(__name__)
- Define a route in your Flask application that will render the HTML template containing the image:
@app.route('/')
def index():
return render_template('index.html')
- Create an HTML template file (e.g.,
index.html
) in a folder called "templates" in your project directory. In this file, you can use theimg
tag to display the image. Set thesrc
attribute of theimg
tag to the relative path of the image file:
<!DOCTYPE html>
<html>
<head>
<title>Flask Image Example</title>
</head>
<body>
<h1>Image Example</h1>
<img src="{{ url_for('static', filename='image.jpg') }}" alt="Image">
</body>
</html>
- Run your Flask application and navigate to the specified route (e.g.,
http://localhost:5000/
). The image should now be displayed on the webpage.
Make sure to replace 'image.jpg'
with the actual filename and extension of your image. You can also adjust the HTML structure and styling of the template to suit your needs.
Remember to have the image file in the correct location within the "static" folder and ensure that the filename and extension match the one specified in the img
tag's src
attribute.
That's it! You have successfully put an image in Flask using the steps above.