Skip to content
Youths Forum Youths Forum Youths Forum

Tech Blogs & Programming Tutorials

Youths Forum Youths Forum Youths Forum

Tech Blogs & Programming Tutorials

  • Blog
  • News
  • Programming
    • PHP
    • JavaScript
    • JQuery
    • CSS
    • HTML
    • API
  • Stock Market Live
  • Automobiles
    • Cars
  • Gadgets
    • Phones
    • Android Phones

Categories

  • Automobiles (12)
    • Cars (7)
  • Blog (103)
    • Poems (2)
    • Space (2)
  • Command (2)
  • Education (2)
  • Entertainment (4)
  • Gadgets (9)
    • Phones (8)
      • Android Phones (4)
  • HTML Templates (11)
  • IT Training Institutes (1)
  • Lifestyle (4)
  • News (51)
  • Others (23)
  • Programming (296)
    • API (16)
    • CSS (83)
    • Database (4)
    • Hosting (1)
    • HTML (37)
    • JavaScript (117)
      • JQuery (27)
      • ReactJS (7)
    • PHP (116)
  • Python (3)
  • recipes (1)
  • SEE Result (1)
  • Server (3)
  • Blog
  • News
  • Programming
    • PHP
    • JavaScript
    • JQuery
    • CSS
    • HTML
    • API
  • Stock Market Live
  • Automobiles
    • Cars
  • Gadgets
    • Phones
    • Android Phones
Close

Search

ProgrammingJavaScript

Image Size Compression Tool using JavaScript

By Admin
January 6, 2025 4 Min Read
0

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.

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!

Tags:

compressorimagejavascript
Author

Admin

Follow Me
Other Articles
Previous

Building a Voice-Controlled YouTube Video Player with JavaScript

Next

Easy Professional Resume Builder using JavaScript

No Comment! Be the first one.

Leave a Reply

Your email address will not be published. Required fields are marked *

FIFA World Cup 2026 Predict and Win by SportsGuff

Recent Posts

  • Unpacking Nepal’s Record Rs 2.12 Trillion Budget and What It Means for You
  • How to Write a Strong Scholarship Application: The Ultimate Step-by-Step Guide
  • How to Prepare for Exams Without Stress: The Ultimate Science-Backed Guide
  • Chiranjibi Adhikari Appointed Acting President of CAN Federation
  • How to Design a Student Marksheet Using HTML and CSS

Tags

adsense ai animate animation animation using HTML and CSS API blog calculator chatgpt Cryptocurrency CSS css animation design Email Facebook featured filemanager file manager free template google htaccess HTML image Instagram interview javascript JQuery jquery ui NADA AutoShow NADA Auto Show 2024 password PHP Progressive Web App PWA QR random react reactjs Rotate travel Twitter vpn youthforum youthsforum youtube

About Us

At Youths Forum, we are passionate about sharing knowledge that empowers students, educators, professionals, and technology enthusiasts.

Our Mission

Our mission is simple: to make technology and education accessible, understandable, and beneficial for everyone. We strive to create content that helps our readers learn new skills and stay updated with industry developments.

RSS RSS

  • Unpacking Nepal’s Record Rs 2.12 Trillion Budget and What It Means for You Admin
  • How to Write a Strong Scholarship Application: The Ultimate Step-by-Step Guide Admin
  • How to Prepare for Exams Without Stress: The Ultimate Science-Backed Guide Admin

Quick Links

  • Stock Market Live
  • Parliament Election 2082
Copyright 2026 — Youths Forum. All rights reserved. Blogsy WordPress Theme