AIイノベーションズ

クライアントサイドのJSで画像を圧縮する Compressor.js

クライアントサイドのJSで画像を圧縮する Compressor.jsの導入と使い方を解説。npmでインストールして、コードを書くだけで圧縮できる。

クライアントでサクッと画像を圧縮したかったので調べたものを共有します。

Compressor.js (GitHub):

https://github.com/fengyuanchen/compressorjs

Compressor.js (画面デモ)

https://fengyuanchen.github.io/compressorjs/

Compressor.jsをインストール

npm i compressorjs

画像ファイルを圧縮する関数

早速コードを紹介しますが、下記のオプションを設定しています。

  • オプション convertSize で 0.8MB 未満に
  • オプション maxWidth で 512px に指定

関数

// 画像ファイルを圧縮する関数
function compressImage(file) {
  return new Promise((resolve, reject) => {
   // 最大ファイルサイズ(bytes)を指定する。この値を超えるファイルは JPEG に変換される
    const maxSizeInBytes = 800 * 1024; // =0.8MB in bytes
 
  // 圧縮する
    new Compressor(file, {
      quality: 0.8,
      convertSize: maxSizeInBytes,
      maxWidth: 512,
      success(result) {
        console.log('Original file size:', file.size / 1024, 'KB');
        console.log('Compressed file size:', result.size / 1024, 'KB');
        console.log('Compressed image width:', result.width, 'px');
        resolve(result);
      },
      error(err) {
        reject(err);
      },
    });
  });
}

使い方

// ファイルが選択されたら自動的に圧縮される
 
const inputElement = document.getElementById('imageInput');
 
inputElement.addEventListener('change', async (event) => {
  const file = event.target.files[0];
  try {
    const compressedFile = await compressImage(file);
    // 圧縮されたファイルを使う (APIに送信したり、画面に表示したり)
  } catch (error) {
    console.error('Compression error:', error);
  }
});

以上です。

On this page