How to Create a Responsive Image Compressor with JavaScript

Learn how to create a responsive and professional image compressor using HTML, JavaScript, and Bootstrap. This step-by-step guide covers everything from building the form to implementing compression functionality.

Tuesday, August 20, 2024
How to Create a Responsive Image Compressor with JavaScript


How to Create a Responsive Image Compressor with HTML, JavaScript, and Bootstrap


Introduction

In today's digital world, optimizing images for the web is crucial for maintaining fast load times and improving user experience. Compressing images without compromising quality is an essential skill for web developers. In this blog post, you'll learn how to create a responsive image compressor using HTML, JavaScript, and Bootstrap. This step-by-step guide will walk you through the process of building a professional-looking image compressor that you can integrate into your website.

Why Compress Images?

Before diving into the code, let's discuss why image compression is so important:

  • Improved Load Times: Compressed images load faster, reducing the overall loading time of your website.
  • Enhanced User Experience: Faster websites lead to better user satisfaction and lower bounce rates.
  • SEO Benefits: Search engines favor faster websites, which can lead to better search engine rankings.
  • Reduced Bandwidth Usage: Compressing images reduces the amount of data that needs to be transferred, saving bandwidth.

Creating the Image Compressor: Step-by-Step Guide

Let's get started on building the image compressor. We'll be using HTML for the structure, Bootstrap for styling, and JavaScript for functionality.

1. Setting Up the HTML Structure

We’ll begin by creating a basic HTML structure with a form that allows users to upload an image, select the compression quality, and compress the image.

2. Adding Styling with CSS

Next, let's add some custom styling to make the page look professional and modern.

3. Implementing Image Compression with JavaScript

Finally, we'll implement the image compression functionality using JavaScript. This script will handle the image upload, compression, and display of the original and compressed images side by side.

HTML Code

DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Image Compressortitle>
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
    <link rel="stylesheet" href="style.css">
    <link rel="preconnect" href="https://fonts.googleapis.com">
    <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
    <link href="https://fonts.googleapis.com/css2?family=Poppins:wght@300;400;600&display=swap" rel="stylesheet">
head>
<body>
    <div class="container mt-5">
        <div class="row justify-content-center">
            <div class="col-md-8">
                <div class="card shadow-sm">
                    <div class="card-body">
                        <h2 class="text-center mb-4">Image Compressorh2>
                        <form id="compressor-form">
                            <div class="form-group">
                                <label for="image-upload" class="btn btn-primary btn-block">
                                    <input type="file" id="image-upload" accept="image/*" required>
                                    Choose an Image
                                label>
                                <p id="original-size" class="text-muted text-center mt-2">p>
                            div>
                            <div class="form-group">
                                <label for="quality">Compression Quality:label>
                                <input type="range" id="quality" class="custom-range" min="0.1" max="1" step="0.1" value="0.7">
                                <span id="quality-value" class="float-right">70%span>
                            div>
                            <button type="submit" class="btn btn-success btn-block">Compress Imagebutton>
                        form>
                    div>
                div>
            div>
        div>

        <div id="output" class="row mt-5" style="display:none;">
            <div class="col-md-6">
                <div class="card shadow-sm">
                    <div class="card-body text-center">
                        <h5>Compressed Imageh5>
                        <a id="download-link" href="#" download="compressed-image.jpg">
                            <img id="compressed-image" src="" class="img-fluid" alt="Compressed Image">
                        a>
                        <p id="compressed-size" class="text-muted mt-2">p>
                        <a id="download-link-btn" href="#" class="btn btn-primary mt-2" download="compressed-image.jpg">Download Compressed Imagea>
                    div>
                div>
            div>
        div>
    div>
    <canvas id="canvas" style="display:none;">canvas>
    <script src="https://code.jquery.com/jquery-3.5.1.slim.min.js">script>
    <script src="https://cdn.jsdelivr.net/npm/@popperjs/core@2.5.3/dist/umd/popper.min.js">script>
    <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js">script>
    <script src="script.js">script>
body>
html>

CSS Code

body {
    font-family: 'Poppins', sans-serif;
    background-color: #f7f7f7;
}

h2 {
    font-weight: 600;
    color: #007bff;
}

.card {
    border-radius: 12px;
    overflow: hidden;
}

#output img {
    max-height: 300px;
    object-fit: cover;
    margin-top: 10px;
}

#original-image, #compressed-image {
    border-radius: 8px;
}

#original-size, #compressed-size {
    font-size: 14px;
}

.btn-primary, .btn-success {
    font-size: 16px;
    padding: 10px 20px;
}

JavaScript Code

document.getElementById('quality').addEventListener('input', function() {
    document.getElementById('quality-value').textContent = Math.round(this.value * 100) + '%';
});

document.getElementById('compressor-form').addEventListener('submit', function(e) {
    e.preventDefault();

    const fileInput = document.getElementById('image-upload');
    const quality = parseFloat(document.getElementById('quality').value);
    const canvas = document.getElementById('canvas');
    const ctx = canvas.getContext('2d');

    if (fileInput.files && fileInput.files[0]) {
        const file = fileInput.files[0];
        document.getElementById('original-size').textContent = `Original Size: ${(file.size / 1024).toFixed(2)} KB`;

        const reader = new FileReader();
       
        reader.onload = function(event) {
            const img = new Image();
            img.onload = function() {
                canvas.width = img.width;
                canvas.height = img.height;
                ctx.drawImage(img, 0, 0, img.width, img.height);

                canvas.toBlob(function(blob) {
                    const compressedImage = URL.createObjectURL(blob);
                    const compressedSize = (blob.size / 1024).toFixed(2);

                    document.getElementById('compressed-image').src = compressedImage;
                    document.getElementById('download-link').href = compressedImage;
                    document.getElementById('compressed-size').textContent = `Compressed Size: ${compressedSize} KB`;

                    document.getElementById('output').style.display = 'block';
                }, 'image/jpeg', quality);
            };
            img.src = event.target.result;
        };
       
        reader.readAsDataURL(file);
    }
});

PHP Code

NO Need

4. Making the Page Responsive

The page layout uses Bootstrap, ensuring that it is fully responsive. The images and content automatically adjust to different screen sizes, providing a seamless experience on both desktop and mobile devices.

Conclusion

With this tutorial, you now have a fully functional and responsive image compressor that you can easily integrate into your website. Whether you're looking to optimize images for faster load times or provide a useful tool for your users, this image compressor is a great addition to any web project.

Leave a Comment: