Building an Image Color Extractor with Flask and JavaScript Preview
Introduction
Have you ever wanted to extract colors from an image using Python? In this tutorial, we'll build a simple Flask-based web app that allows users to upload an image, preview it instantly, and extract its dominant colors using extcolors
.
This project will include:
✅ Instant Image Preview using JavaScript
✅ Flask Backend for Image Processing
✅ Dynamic Color Extraction from Images
✅ A Stylish UI with TailwindCSS
By the end, you'll have a fully functional Flask app that extracts colors from an image and displays them in real time.
📌 GitHub Repository: LEO-MAhendra/leo-color007
1. Setting Up the Project
Install Dependencies
First, create a virtual environment and install the required libraries:
pip install flask pillow extcolors
2. Creating the Flask Backend
We'll use Flask to handle image uploads and process the colors using extcolors
.
Flask Application (app.py
)
import osimport PILimport extcolorsfrom flask import Flask, render_template, request
app = Flask(__name__)
UPLOAD_DIRECTORY = "./static/images/"
def get_color(name): img = PIL.Image.open(name) colors, pixel_count = extcolors.extract_from_image(img) rbgvalues = [color[0] for color in colors if isinstance(color, tuple)] return rbgvalues
@app.route("/")def index(): return render_template("index.html")
@app.route("/upload", methods=["POST"])def upload(): if "image" not in request.files: return "No file uploaded", 400
image = request.files["image"] allowed_extensions = {"jpg", "jpeg", "png"} if image.filename.split(".")[-1].lower() not in allowed_extensions: return "Invalid file extension", 400 if not os.path.exists(UPLOAD_DIRECTORY): os.makedirs(UPLOAD_DIRECTORY) tempfile = f"temp.{image.filename.split('.')[-1].lower()}" fileloc = os.path.join(UPLOAD_DIRECTORY, tempfile)
image.save(fileloc) colors = get_color(fileloc) return render_template("index.html", filename=fileloc, values=colors)
if __name__ == "__main__": app.run()
3. Building the Frontend
We’ll use TailwindCSS for styling and JavaScript for real-time image preview.
HTML File (templates/index.html
)
4. Running the Project
Here's an updated blog post section with Poetry setup, requirements.txt installation, and a reference to your Django environment setup blog.
4. Setting Up the Environment
Before running the Flask app, we need to set up the Python environment.
Option 1: Using Poetry (Recommended)
Since we use Poetry for dependency management, you can install the required dependencies using:
poetry install
If you haven’t set up the environment yet, follow these steps:
poetry init # Initialize a new Poetry environment
poetry add flask pillow extcolors # Install required dependencies
poetry shell # Activate the virtual environment
Option 2: Using a Virtual Environment and requirements.txt
If you prefer a traditional virtual environment, follow these steps:
python -m venv venv # Create a virtual environment
source venv/bin/activate # Activate (Mac/Linux)
venv\Scripts\activate # Activate (Windows)
pip install -r requirements.txt # Install dependencies
Your requirements.txt
should include:
gunicornOnce the environment is set up, start your Flask app with:
python app.py
Then open http://127.0.0.1:5000/ in your browser and test the upload functionality.
Django Environment Setup (For Future Reference)
If you are also working with Django, you can follow my blog on setting up the Django environment with Poetry:
🔗 Django Commands and Environment Setup
In this tutorial, we built a Flask web app that extracts colors from an image using extcolors
.
We also added instant preview functionality using JavaScript, ensuring a smooth user experience. 🚀
🔗 GitHub Repository: LEO-MAhendra/leo-color007
0 Comments