Client-side Image Compressor In Vanilla JavaScript

Category: Image , Javascript | April 29, 2024
AuthorLenni009
Last UpdateApril 29, 2024
LicenseMIT
Tags
Views84 views
Client-side Image Compressor In Vanilla JavaScript

This is a simple JavaScript-powered image compressor that allows you to compress images directly on the client-side (browser) without the need for server-side processing.

It is perfect for situations where you need to compress images before uploading them to a server. It helps reduce file sizes, leading to faster upload times and less bandwidth usage.

This Image Compressor works by converting the image file to a bitmap and then compressing it using a web worker. This process happens in parallel to ensure efficient compression without blocking the main thread. The compressed image is then returned as a blob, ready for upload or further processing.

How to use it:

1. Install & download the Image Compressor using NPM.

npm i simple-image-compressor
import { compressImage } from 'simple-image-compressor';

2. Alternatively, you can include the compiled JavaScript directly in your HTML:

<script src="/dist/simple-image-compressor-min.js"></script>

3. Use the compressImage function to compress your image:

const options = {
      // Adjust the quality as needed (0 - 1)
      quality: 0.9,
      // Or 'image/webp' for webp format
      type: 'image/jpeg',
};
const res = await compressImage(file, options);

4. You can also import imageTypes alongside compressImage to specify the desired output format:

import { imageTypes, compressImage } from 'simple-image-compressor';
const imageTypes = {
      WEBP: 'image/webp',
      JPEG: 'image/jpeg',
};

You Might Be Interested In:


Leave a Reply