0
0
Flaskframework~8 mins

Serving images in Flask - Performance & Optimization

Choose your learning style9 modes available
Performance: Serving images
HIGH IMPACT
This affects page load speed by controlling how quickly images appear and how much data the browser downloads.
Serving images in a Flask web app
Flask
from flask import Flask, send_from_directory
app = Flask(__name__)

@app.route('/image')
def image():
    response = send_from_directory('static', 'optimized_image.webp')
    response.cache_control.max_age = 86400  # cache for 1 day
    return response
Serving compressed, optimized images with cache headers reduces load time and bandwidth.
📈 Performance Gainreduces image size by 50-80%, enables browser caching, speeds up LCP
Serving images in a Flask web app
Flask
from flask import Flask, send_file
app = Flask(__name__)

@app.route('/image')
def image():
    return send_file('static/large_image.png')
Serving large images without compression or caching causes slow load times and high bandwidth use.
📉 Performance Costblocks rendering until full image loads, adds large file size to transfer
Performance Comparison
PatternDOM OperationsReflowsPaint CostVerdict
Serving large uncompressed imagesMinimal0High decode and paint cost[X] Bad
Serving optimized compressed images with cachingMinimal0Low decode and paint cost[OK] Good
Rendering Pipeline
The browser requests the image, the server sends the file, then the browser decodes and paints it. Optimized images reduce decoding and painting time.
Network
Decode
Paint
⚠️ BottleneckNetwork transfer and decode time for large images
Core Web Vital Affected
LCP
This affects page load speed by controlling how quickly images appear and how much data the browser downloads.
Optimization Tips
1Always serve images in compressed formats like WebP or optimized JPEG/PNG.
2Set cache headers to enable browser caching of images.
3Resize images to the display size needed to avoid extra data transfer.
Performance Quiz - 3 Questions
Test your performance knowledge
What is the main benefit of serving compressed images in a Flask app?
AIncreased image quality
BMore CPU usage on the server
CFaster page load and reduced bandwidth
DLonger caching times always hurt performance
DevTools: Network
How to check: Open DevTools, go to Network tab, reload page, filter by Images, check image file sizes and load times.
What to look for: Look for large image sizes and long load times indicating poor optimization; smaller sizes and fast loads indicate good performance.