KMeans Image Compression Web App
A web application that uses K-means clustering to compress images by reducing the number of colors. The application features a responsive design with light and dark mode, and allows users to upload, compress, and download images.
Features
- Upload images via drag-and-drop or file browser
- Adjust the number of colors for compression (2-64)
- View before and after comparison
- Download or copy the compressed image
- Light and dark mode support
- Responsive design for mobile and desktop
Tech Stack
Frontend
- React with Vite
- Tailwind CSS for styling
- Lucide React for icons
Backend
- Express.js
- Python for K-means implementation
- Multer for file handling
Installation and Setup
Prerequisites
- Node.js (v14 or higher)
- Python (v3.7 or higher)
- npm or yarn
Setup Instructions
1. Clone the repository (or create from scratch)
Create the project structure:
kmeans-compressor/
├── frontend/
└── backend/
2. Frontend Setup
cd frontend
npm init vite@latest . -- --template react
npm install
npm install tailwindcss autoprefixer lucide-react
npx tailwindcss init -p
Copy the provided frontend code files to their respective locations.
3. Backend Setup
cd ../backend
npm init -y
npm install express cors multer
npm install --save-dev nodemon
Create a Python virtual environment (recommended):
python -m venv venv
source venv/bin/activate # On Windows: venv\Scripts\activate
pip install -r requirements.txt
Copy the provided backend code files to their respective locations.
4. Running the Application
Start the backend:
cd backend
npm run dev
In a separate terminal, start the frontend:
cd frontend
npm run dev
The application should now be running at http://localhost:5173 with the backend API at http://localhost:5000.
Usage
- Open the application in your web browser
- Upload an image using drag-and-drop or by clicking the upload area
- Adjust the number of colors using the slider (fewer colors = more compression)
- Click "Compress Image" to process the image
- Once processing is complete, you can download or copy the compressed image
- Toggle between light and dark mode using the button in the top-right corner
How It Works
The application uses the K-means clustering algorithm to reduce the number of colors in an image. The process works as follows:
- The image is uploaded to the server
- The image is converted to a matrix of RGB values
- K-means clustering is used to identify the most representative colors
- Each pixel is assigned to its closest centroid (representative color)
- The image is reconstructed using only the representative colors
- The compressed image is sent back to the client