Javascript module to be run in the web browser for image compression. You can use this module to compress jpeg and png image by reducing resolution or storage size before uploading to application server to save bandwidth.
npm install browser-image-compression --save
or
yarn add browser-image-compression
(can be used in framework like React, Angular, Vue etc)
(work with bundler like webpack and rollup)
import imageCompression from 'browser-image-compression';
or
<script type="text/javascript" src="path/to/dist/browser-image-compression.js"></script>
<input type="file" accept="image/*" onchange="handleImageUpload(event);">
function handleImageUpload(event) {
var imageFile = event.target.files[0];
console.log('originalFile instanceof Blob', imageFile instanceof Blob); // true
console.log(`originalFile size ${imageFile.size / 1024 / 1024} MB`);
var maxSizeMB = 1;
var maxWidthOrHeight = 1920; // compressedFile will scale down by ratio to a point that width or height is smaller than maxWidthOrHeight
imageCompression(imageFile, maxSizeMB, maxWidthOrHeight) // maxSizeMB, maxWidthOrHeight are optional
.then(function (compressedFile) {
console.log('compressedFile instanceof Blob', compressedFile instanceof Blob); // true
console.log(`compressedFile size ${compressedFile.size / 1024 / 1024} MB`); // smaller than maxSizeMB
return uploadToServer(compressedFile); // write your own logic
})
.catch(function (error) {
console.log(error.message);
});
}
with async/await syntax:
async function handleImageUpload(event) {
const imageFile = event.target.files[0];
console.log('originalFile instanceof Blob', imageFile instanceof Blob); // true
console.log(`originalFile size ${imageFile.size / 1024 / 1024} MB`);
const maxSizeMB = 1;
const maxWidthOrHeight = 1920; // compressedFile will scale down by ratio to a point that width or height is smaller than maxWidthOrHeight
try {
const compressedFile = await imageCompression(imageFile, maxSizeMB); // maxSizeMB, maxWidthOrHeight are optional
console.log('compressedFile instanceof Blob', compressedFile instanceof Blob); // true
console.log(`compressedFile size ${compressedFile.size / 1024 / 1024} MB`); // smaller than maxSizeMB
await uploadToServer(compressedFile); // write your own logic
} catch (error) {
console.log(error);
}
}
IE / Edge |
Firefox |
Chrome |
Safari |
Opera |
Chrome for Android |
---|---|---|---|---|---|
IE10, IE11, Edge | last 2 versions | last 2 versions | last 2 versions | last 2 versions | last 2 versions |
Please check the "example" folder in this repo