Image Size Compression Tool using JavaScript

0
31

In today’s digital landscape, image optimization plays a crucial role in improving website performance, reducing load times, and enhancing user experience. With the growing emphasis on faster web applications, image size compression tools have become indispensable. JavaScript, being one of the most versatile web technologies, provides powerful capabilities to handle image compression directly in the browser.

The Importance of Image Compression

High-resolution images are often essential for delivering visually appealing content, but they come with a significant drawback: large file sizes. These large image files can slow down website loading speeds, negatively impact SEO rankings, and frustrate users. Image compression reduces file size without compromising the visual quality, ensuring websites are faster and more efficient.

Follow this video for complete guidance :

Full Source Code

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Image Compressor</title>
    <style>
        :root {
            --primary: #4f46e5;
            --primary-hover: #4338ca;
            --background: #f1f5f9;
            --card: #ffffff;
        }

        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        body {
            font-family: system-ui, -apple-system, sans-serif;
            background: var(--background);
            min-height: 100vh;
            display: grid;
            place-items: center;
            padding: 1rem;
        }

        .container {
            background: var(--card);
            width: min(1200px, 100%);
            height: min(800px, 100vh - 2rem);
            border-radius: 1rem;
            box-shadow: 0 4px 6px -1px rgb(0 0 0 / 0.1);
            display: flex;
            flex-direction: column;
            gap: 1rem;
            padding: 1.5rem;
            position: relative;
        }

        .header {
            text-align: center;
            margin-bottom: 0.5rem;
        }

        .header h1 {
            font-size: 1.75rem;
            font-weight: 600;
            background: linear-gradient(45deg, var(--primary), #818cf8);
            -webkit-background-clip: text;
            -webkit-text-fill-color: transparent;
        }

        .dropzone {
            border: 2px dashed #cbd5e1;
            border-radius: 0.75rem;
            height: 160px;
            display: flex;
            align-items: center;
            justify-content: center;
            cursor: pointer;
            transition: all 0.2s;
            background: var(--background);
        }

        .dropzone p {
            font-size: 1.25rem;
            color: #64748b;
        }

        .dropzone:hover {
            border-color: var(--primary);
            background: #f8fafc;
        }

        .preview-container {
            flex: 1;
            position: relative;
            overflow: hidden;
            border-radius: 0.75rem;
            background: var(--background);
        }

        .preview-container img {
            width: 100%;
            height: 100%;
            object-fit: contain;
            transition: transform 0.3s;
        }

        .preview-container:hover img {
            transform: scale(1.02);
        }

        .compression-overlay {
            position: absolute;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%);
            background: rgba(0, 0, 0, 0.85);
            color: white;
            padding: 0.75rem 1.5rem;
            border-radius: 0.5rem;
            font-size: 1.5rem;
            font-weight: bold;
            backdrop-filter: blur(4px);
            box-shadow: 0 4px 6px rgb(0 0 0 / 0.1);
        }

        button {
            background: var(--primary);
            color: white;
            border: none;
            padding: 0.75rem 1.5rem;
            border-radius: 0.5rem;
            cursor: pointer;
            font-size: 1rem;
            font-weight: 500;
            transition: all 0.2s;
            width: 100%;
        }

        button:hover {
            background: var(--primary-hover);
            transform: translateY(-1px);
        }

        @media (max-width: 640px) {
            .container {
                height: calc(100vh - 2rem);
                padding: 1rem;
            }
            
            .dropzone {
                height: 120px;
            }

            .dropzone p {
                font-size: 1rem;
                padding: 0 1rem;
                text-align: center;
            }
        }
    </style>
</head>
<body>
    <div class="container">
        <div class="header">
            <h1>Image Compressor</h1>
        </div>

        <div class="dropzone" id="dropzone">
            <p>Drop your image here or click to browse</p>
            <input type="file" id="imageInput" accept="image/*" hidden>
        </div>

        <div class="preview-container" id="imageProcessingArea" style="display: none;">
            <img id="outputImage" alt="Compressed Image">
            <div class="compression-overlay" id="compressionOverlay">0% Compressed</div>
        </div>

        <button id="downloadBtn" style="display: none;">Download Compressed Image</button>
    </div>

    <script>
        const dropzone = document.getElementById('dropzone');
        const imageInput = document.getElementById('imageInput');
        const imageProcessingArea = document.getElementById('imageProcessingArea');
        const outputImage = document.getElementById('outputImage');
        const downloadBtn = document.getElementById('downloadBtn');
        const compressionOverlay = document.getElementById('compressionOverlay');

        let currentFile = null;

        dropzone.addEventListener('dragover', (e) => {
            e.preventDefault();
            dropzone.classList.add('drag-over');
        });

        dropzone.addEventListener('dragleave', () => {
            dropzone.classList.remove('drag-over');
        });

        dropzone.addEventListener('drop', (e) => {
            e.preventDefault();
            dropzone.classList.remove('drag-over');
            const file = e.dataTransfer.files[0];
            if (file && file.type.startsWith('image/')) {
                processImage(file);
            }
        });

        dropzone.addEventListener('click', () => {
            imageInput.click();
        });

        imageInput.addEventListener('change', (e) => {
            const file = e.target.files[0];
            if (file && file.type.startsWith('image/')) {
                processImage(file);
            }
        });

        function processImage(file) {
            currentFile = file;
            compressImage(file, 0.8);
        }

        function compressImage(file, quality) {
            const img = new Image();
            img.src = URL.createObjectURL(file);
            img.onload = () => {
                const canvas = document.createElement('canvas');
                canvas.width = img.width;
                canvas.height = img.height;
                const ctx = canvas.getContext('2d');
                ctx.drawImage(img, 0, 0);

                canvas.toBlob((blob) => {
                    const url = URL.createObjectURL(blob);
                    outputImage.src = url;
                    imageProcessingArea.style.display = 'block';
                    downloadBtn.style.display = 'block';

                    const compressionRatio = ((1 - (blob.size / file.size)) * 100).toFixed(1);
                    compressionOverlay.textContent = `${compressionRatio}% Compressed`;

                    downloadBtn.onclick = () => {
                        const a = document.createElement('a');
                        a.href = url;
                        a.download = `compressed_${file.name}`;
                        a.click();
                    };
                }, 'image/jpeg', quality);
            };
        }
    </script>
</body>
</html>

Why Use JavaScript for Image Compression?

JavaScript-based image compression tools offer several advantages:

  • Client-Side Processing: Compression occurs directly in the user’s browser, reducing server load.
  • Real-Time Compression: Users can instantly preview compressed images.
  • Easy Integration: JavaScript libraries and APIs make it seamless to integrate image compression into web applications.
  • User-Friendly Interfaces: Interactive UI components, such as drag-and-drop zones, simplify the user experience.
ALSO READ  Play Musical Notes with JavaScript

Key Features of a JavaScript Image Compression Tool

An effective JavaScript image compression tool typically includes:

  • Drag-and-Drop Uploads: Users can quickly upload images.
  • Dynamic Compression Levels: Adjustable compression quality to balance size and clarity.
  • Preview Feature: Real-time previews to visualize the output.
  • Download Option: Compressed images can be saved effortlessly.
  • Browser Compatibility: Works across modern browsers.

Building an Image Compression Tool with JavaScript

Developing an image compression tool involves:

  • File Input Handling: Using fields to upload images.
  • Canvas API: JavaScript’s Canvas API is essential for manipulating and compressing images.
  • Blob Conversion: Converting canvas data to downloadable files.
  • User Feedback: Displaying compression percentage and success messages.

Advantages of Client-Side Compression

  • Reduced Server Load: No need to process images on the server.
  • Instant Results: Users can see compressed images in real time.
  • Increased Privacy: Images are processed locally without being uploaded.

Use Cases for JavaScript Image Compression Tools

  • Content Management Systems (CMS): Automatic image compression during uploads.
  • E-Commerce Platforms: Optimize product images to improve loading speeds.
  • Portfolio Websites: Maintain high-quality visuals with reduced file sizes.
  • Social Media Platforms: Ensure faster image uploads and sharing

JavaScript-powered image compression tools are a game-changer for web developers and content creators. They offer a balance between image quality and performance without requiring advanced server configurations. By leveraging modern JavaScript APIs, developers can create highly efficient image compression tools that deliver exceptional user experiences.

Whether you’re building a blog, an online store, or a portfolio site, implementing JavaScript-based image compression will not only boost your website’s performance but also leave a lasting impression on your audience. Start optimizing your images today and stay ahead in the digital race!

ALSO READ  Detect Keyboard key press using JavaScript

Comments are closed.