DEV Community

Cover image for This is the best way to compress images on a website.
William Bojczuk
William Bojczuk

Posted on

This is the best way to compress images on a website.

Any website or app that allows users to upload their own photos needs to have a compression system in place. Which one should I use? I tried out different packages so you wouldn’t have to.

Why do you need a compression system?

The real question is, why wouldn’t you? Due to improvements in camera quality comes larger photo sizes. I saw this firsthand in my latest project that allows a user to upload images to their blog. During tests, I realized that from an IPhone 14, photos could easily reach 8 to 11 Megabytes. That’s massive, and too big to be serving to visitors on a website. A compression system can
take your photo and reduce the quality within a certain threshold as well as apply image dimension restraints to save that precious storage.

How you can implement this system.

I tried a few different frameworks and came to the conclusion that this one was the easiest to use and provided the desired settings. Image Resize Compress can be installed through NPM if you’re familiar with it npm i image-resize-compress, or you can simply include the package’s CDN to use the script <script src=”https://cdn.jsdelivr.net/npm/image-resize-compress@1/dist/index.js"></script>. The settings are really straightforward so I wrote up a quick function for you to get started quickly.

async function compressImage(image, settings){
    const curSettings = {
        quality: 75,
        width: "auto",
        height: "auto",
        format: "jpg",
        ...settings
    }
    const compressRes = await fromBlob(image, curSettings.quality, curSettings.width, curSettings.height, curSettings.format);
    return compressRes;
}


// Using The Function
compressImage(file, {quality: 80, height: 720})
.then((res)=>{
    const compressedImage = res;
})
Enter fullscreen mode Exit fullscreen mode

You simply call the function with the input image as the first parameter, and then any settings you want to alter as an object in the second parameter. The default quality is 75, or 75%. the height and width settings are set to auto meaning that the original dimensions will be used, and the default format is jpg but webp, png, bmp, and _gif_are also available.

You do have to keep in mind that this function returns a Promise. Which is why I used .then() to access the resolution (aka the data).

This package is really easy to use and allows you to not only compress the image but to also resize extremely large images to preset dimensions. If you want to learn more about the package, check out its documentation here.

Thanks for reading! For more tips, tricks and tutorials follow me on YouTube or Instagram.

Make sure and leave a comment if you want to see me cover something specific.

Thumbnail: https://freeicons.io/profile/6156

Top comments (0)