Introduction
In this tutorial, we will learn how to compress image files using JavaScript without uploading them to the server. This technique helps in reducing image size before uploading, improving website performance and user experience. Below, you can find the complete source code and a demo preview.
Live Demo
How It Works
We will use the canvas element and toBlob() or toDataURL() methods to compress images directly in the browser before uploading or downloading them. Users can select an image file, define the quality level, and download the optimized version.
Full Source Code
<!doctype html>
<html lang="en">
<head>
<!-- Required meta tags -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<!-- Bootstrap CSS -->
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous">
<title>Compress Image using Vanilla JavaScript</title>
</head>
<body>
<div class="container">
<h1 class="mt-5 mb-5 text-center"><b>Compress Image using Vanilla JavaScript</b></h1>
<div class="card">
<div class="card-header">Select Image</div>
<div class="card-body">
<div class="row">
<div class="col-md-4">
<label>Select Image</label>
<input type="file" id="imageInput" accept="image/*" />
</div>
<div class="col-md-2">
<label>Image Quality</label>
<input type="number" min="1" max="100" id="qualityInput" value="80" />
</div>
<div class="col-md-2">
<button class="btn btn-primary" onclick="optimizeImage()">Optimize & Download</button>
</div>
</div>
</div>
</div>
</div>
<canvas id="canvas" style="display:none;"></canvas>
<img id="preview" alt="Optimized Image Preview" class="img-thumbnail img-fluid" style="display:none;">
<!-- Option 1: Bootstrap Bundle with Popper -->
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/js/bootstrap.bundle.min.js" integrity="sha384-MrcW6ZMFYlzcLA8Nl+NtUVF0sA7MsXsP1UyJoMp4YLEuNSfAP+JcXn/tWtIaxVXM" crossorigin="anonymous"></script>
</body>
</html>
<script>
function optimizeImage(){
//Getting the Image File
const fileInput = document.getElementById('imageInput').files[0];
//Checking If Image is Selected
if(!fileInput){
alert('Please select an image first.');
return;
}
//Getting Image Quality
let quality = document.getElementById('qualityInput').value;
//Defining Image Format
const format = 'image/jpeg';
//Validating Image Quality
if(quality < 1 || quality > 100 || isNaN(quality)){
alert('Image quality must be between 1 and 100.');
return;
}
//Reading the Image File
const reader = new FileReader();
//Handling Image Load
reader.onload = function(event) {
//Creating an Image Object
const img = new Image();
img.src = event.target.result;
//Handling Image Load in Canvas
img.onload = function(){
//Getting the Canvas and Context
const canvas = document.getElementById('canvas');
const ctx = canvas.getContext('2d');
//Setting Canvas Dimensions
let newWidth = img.width;
let newHeight = img.height;
canvas.width = newWidth;
canvas.height = newHeight;
ctx.drawImage(img, 0, 0, newWidth, newHeight);
//Compressing and Creating Blob
canvas.toBlob(function(blob){
//Creating a Downloadable URL
const optimizedURL = URL.createObjectURL(blob);
// Display preview image
const preview = document.getElementById('preview');
preview.src = optimizedURL;
preview.style.display = "block";
//Downloading the Compressed Image
const a = document.createElement('a');
a.href = optimizedURL;
a.download = 'optimized-image.' + format.split("/")[1];
a.click();
}, format, quality / 100);
};
};
reader.readAsDataURL(fileInput);
}
</script>
Conclusion
Using JavaScript to compress images on the client side can help optimize web performance and save bandwidth. This method is useful for web applications, social media platforms, and e-commerce sites where image size matters. Try implementing it in your projects and share your feedback!
If you found this tutorial helpful, don’t forget to like, share, and subscribe to our YouTube channel for more web development tutorials.
0 comments:
Post a Comment