Image size reducer using python

NotzNotz
3 min read

How to Create an Image Size Reducer Website Using Python

Reducing image size without losing too much quality is crucial for web optimization, faster load times, and saving bandwidth. In this tutorial, we'll walk you through creating a simple image size reducer website using Python with Flask for the backend and Pillow for image processing.

By the end, you'll have a web app where users can upload images and get a compressed version for download.


๐Ÿงฐ Tools & Technologies

  • Python 3.x

  • Flask โ€“ lightweight web framework

  • Pillow โ€“ Python Imaging Library (PIL Fork)

  • HTML/CSS โ€“ Frontend

  • Bootstrap โ€“ Optional for quick styling


๐Ÿ“ฆ Step 1: Setup Your Environment

Create a folder for your project:

bashCopyEditmkdir image-resizer
cd image-resizer

Set up a virtual environment (optional but recommended):

bashCopyEditpython -m venv venv
source venv/bin/activate  # Windows: venv\Scripts\activate

Install required packages:

bashCopyEditpip install Flask Pillow

๐Ÿ“ Project Structure

arduinoCopyEditimage-resizer/
โ”‚
โ”œโ”€โ”€ app.py
โ”œโ”€โ”€ static/
โ”‚   โ””โ”€โ”€ uploads/
โ”œโ”€โ”€ templates/
โ”‚   โ”œโ”€โ”€ index.html
โ”‚   โ””โ”€โ”€ result.html

๐Ÿง  Step 2: Create the Flask App (app.py)

pythonCopyEditfrom flask import Flask, render_template, request, send_from_directory
from PIL import Image
import os
import uuid

app = Flask(__name__)
UPLOAD_FOLDER = 'static/uploads'
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER

# Ensure upload directory exists
os.makedirs(UPLOAD_FOLDER, exist_ok=True)

@app.route('/', methods=['GET', 'POST'])
def index():
    if request.method == 'POST':
        image = request.files['image']
        quality = int(request.form.get('quality', 70))
        if image:
            filename = f"{uuid.uuid4().hex}.jpg"
            filepath = os.path.join(app.config['UPLOAD_FOLDER'], filename)

            # Open and compress the image
            img = Image.open(image)
            img = img.convert('RGB')  # Ensure it's JPEG-compatible
            img.save(filepath, optimize=True, quality=quality)

            return render_template('result.html', filename=filename)
    return render_template('index.html')

@app.route('/download/<filename>')
def download_file(filename):
    return send_from_directory(app.config['UPLOAD_FOLDER'], filename, as_attachment=True)

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

๐ŸŒ Step 3: Create Frontend Templates

templates/index.html

htmlCopyEdit<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Image Size Reducer</title>
  <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css">
</head>
<body class="container py-5">
  <h2 class="mb-4">Reduce Your Image Size</h2>
  <form method="POST" enctype="multipart/form-data">
    <div class="mb-3">
      <input type="file" name="image" accept="image/*" required class="form-control">
    </div>
    <div class="mb-3">
      <label for="quality">Quality (1-100):</label>
      <input type="number" name="quality" min="1" max="100" value="70" class="form-control" required>
    </div>
    <button type="submit" class="btn btn-primary">Compress Image</button>
  </form>
</body>
</html>

templates/result.html

htmlCopyEdit<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Image Compressed</title>
  <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css">
</head>
<body class="container py-5">
  <h2>Your Compressed Image</h2>
  <img src="{{ url_for('static', filename='uploads/' + filename) }}" class="img-fluid my-3" alt="Compressed">
  <br>
  <a href="{{ url_for('download_file', filename=filename) }}" class="btn btn-success">Download Image</a>
  <br><br>
  <a href="/" class="btn btn-secondary">Compress Another</a>
</body>
</html>

๐Ÿš€ Step 4: Run the App

Run the server:

bashCopyEditpython app.py

Open your browser and go to http://127.0.0.1:5000/.


โœ… Features You Can Add

  • Drag-and-drop image upload

  • Resize by dimensions

  • Support for multiple file types

  • Upload progress bar

  • History of recent downloads


๐ŸŽฏ Conclusion

In just a few steps, we built a functioning image compressor web app using Python and Flask. With Pillow, image compression is quick and effective, and Flask makes web integration simple and elegant.

Want to make it production-ready? Deploy on Heroku, Render, or Railway with a few configuration tweaks.

0
Subscribe to my newsletter

Read articles from Notz directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Notz
Notz