how to get images on flask page
To get images on a Flask page, you can follow these steps:
- Import Flask and create an instance of the Flask class.
from flask import Flask
app = Flask(__name__)
- Create a route decorator using the
@app.route()
decorator. This will define the URL path for the route.
@app.route('/')
def home():
return 'Home Page'
- In the route function, use the
send_file()
function from Flask to send the image file to the client.
from flask import send_file
@app.route('/image')
def get_image():
return send_file('path/to/image.jpg', mimetype='image/jpg')
Save the image file in a folder within your Flask application directory. In this example, the image file is named "image.jpg" and is located in the "static" folder.
In the HTML template, use the
<img>
tag to display the image. Set thesrc
attribute to the URL of the image route.
<!DOCTYPE html>
<html>
<head>
<title>Image Example</title>
</head>
<body>
<img src="{{ url_for('get_image') }}" alt="Image">
</body>
</html>
- Run the Flask application.
if __name__ == '__main__':
app.run()
- Access the Flask application in a web browser and navigate to the specified route, such as
http://localhost:5000/image
. The image will be displayed on the page.
Note: Make sure to replace 'path/to/image.jpg'
with the actual path to your image file. Also, ensure that the image file is in a format supported by web browsers, such as JPEG or PNG.