Reducing resolution or storage size of Image before uploading to the application server Easily

Tohid haghighi
4 min readJan 17, 2024

High-quality images go a long way in impressing your website visitors. However, they can slow down your website and hamper your user experience. So, it helps compress these images in file size to remain appealing to the users without hindering UX.

Image compression can be done in two ways — lossy or lossless.

Image compression

What is lossy image compression?

Lossy compression is where the original image file is removed and replaced with the compressed image file. Since the original image cannot be restored, it is also referred to as irreversible compression. However, if done correctly, the data loss is not usually noticeable.

What is lossless image compression?

On the other hand, lossless compression does not lose data in the process. Instead, it “packs” the data into smaller sizes. Imagine writing a logo para in shorthand that a system can read and understand. Lossless compression is akin to that.

Lossless compression is favored for archiving purposes because it can retain the original asset without resulting in data loss. It is often used in medical imaging, technical drawings, clip art, comics, etc.

In addition to these techniques, you can compress images using JavaScript and dedicated tools.

This tutorial will look at compressing images using browser-image-compression JavaScript library.‌‌

Why do you need image compression?

Image compression delivers several benefits, including:

✅Reduced file size

The most fundamental benefit of image compression is that it reduces file size. You can keep compressing the image until it’s the size you want, depending on the sort of file you’re squeezing.

✅SEO-friendliness

Google search engines use the loading speeds of online pages to rank web pages. As a result, the lower the image weight, the higher the web’s score and the chances of scoring higher SERPs.

✅Faster website loading speed

Using images that are less in weight will help the web load faster on mobile phones. Google does more weightage to websites that perform well on mobile devices.

Also, some web hosting firms also require compressed images to develop websites that load faster than their competitors.

Now that we know the need for image compression let’s get cut to the chase on how to do it using Canvas.

Implement Image Compression

<input type="file" accept="image/*" onchange="handleImageUpload(event);">
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 options = {
maxSizeMB: 1,
maxWidthOrHeight: 1920,
useWebWorker: true,
}
try {
const compressedFile = await imageCompression(imageFile, options);
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);
}

}
// you should provide one of maxSizeMB, maxWidthOrHeight in the options
const options: Options = {
maxSizeMB: number, // (default: Number.POSITIVE_INFINITY)
maxWidthOrHeight: number, // compressedFile will scale down by ratio to a point that width or height is smaller than maxWidthOrHeight (default: undefined)
// but, automatically reduce the size to smaller than the maximum Canvas size supported by each browser.
// Please check the Caveat part for details.
onProgress: Function, // optional, a function takes one progress argument (percentage from 0 to 100)
useWebWorker: boolean, // optional, use multi-thread web worker, fallback to run in main-thread (default: true)
libURL: string, // optional, the libURL of this library for importing script in Web Worker (default: https://cdn.jsdelivr.net/npm/browser-image-compression/dist/browser-image-compression.js)
preserveExif: boolean, // optional, use preserve Exif metadata for JPEG image e.g., Camera model, Focal length, etc (default: false)

signal: AbortSignal, // optional, to abort / cancel the compression

// following options are for advanced users
maxIteration: number, // optional, max number of iteration to compress the image (default: 10)
exifOrientation: number, // optional, see https://stackoverflow.com/a/32490603/10395024
fileType: string, // optional, fileType override e.g., 'image/jpeg', 'image/png' (default: file.type)
initialQuality: number, // optional, initial quality value between 0 and 1 (default: 1)
alwaysKeepResolution: boolean // optional, only reduce quality, always keep width and height (default: false)
}

imageCompression(file: File, options: Options): Promise<File>
function handleImageUpload(event) {

var imageFile = event.target.files[0];

var controller = new AbortController();

var options = {
// other options here
signal: controller.signal,
}
imageCompression(imageFile, options)
.then(function (compressedFile) {
return uploadToServer(compressedFile); // write your own logic
})
.catch(function (error) {
console.log(error.message); // output: I just want to stop
});

// simulate abort the compression after 1.5 seconds
setTimeout(function () {
controller.abort(new Error('I just want to stop'));
}, 1500);
}

--

--

Tohid haghighi

Full-Stack Developer | C# | .NET Core | Vuejs | TDD | Javascript