0
0
Flaskframework~5 mins

Serving images in Flask

Choose your learning style9 modes available
Introduction

Serving images lets your web app show pictures to users. It makes your site more interesting and useful.

You want to display a logo or icon on your website.
You need to show user-uploaded photos in a profile page.
You want to serve product images in an online store.
You want to serve static images like backgrounds or banners.
You want to serve images stored on your server to web pages.
Syntax
Flask
from flask import Flask, send_from_directory

app = Flask(__name__)

@app.route('/images/<filename>')
def serve_image(filename):
    return send_from_directory('images', filename)

send_from_directory sends files from a folder safely.

The folder name is relative to your app's root folder.

Examples
Serve images from a subfolder static/img using a URL path /img/filename.
Flask
from flask import Flask, send_from_directory

app = Flask(__name__)

@app.route('/img/<filename>')
def image(filename):
    return send_from_directory('static/img', filename)
Serve a single image file directly with send_file.
Flask
from flask import Flask, send_file

app = Flask(__name__)

@app.route('/logo')
def logo():
    return send_file('static/logo.png', mimetype='image/png')
Sample Program

This app shows a simple page with an image. The image is served from the images folder on the server.

Flask
from flask import Flask, send_from_directory

app = Flask(__name__)

@app.route('/')
def home():
    return '''
    <html>
      <body>
        <h1>Welcome!</h1>
        <img src="/images/sample.jpg" alt="Sample Image" />
      </body>
    </html>
    '''

@app.route('/images/<filename>')
def serve_image(filename):
    return send_from_directory('images', filename)

if __name__ == '__main__':
    app.run(debug=True)
OutputSuccess
Important Notes

Put your images in the folder you specify (here, 'images').

Use alt text in <img> tags for accessibility.

For production, consider using a web server or CDN to serve images efficiently.

Summary

Serving images lets your Flask app show pictures to users.

Use send_from_directory to serve image files from a folder.

Make sure images are in the right folder and use proper URLs in your HTML.