0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

JavaScriptだけで画像をWebPに一括変換する実装メモ(外部送信なし・Canvas toBlob 活用)

0
Posted at

はじめに

Webサイトの表示速度改善(Core Web Vitals対策)で定番となったWebP形式ですが、制作現場では次のような悩みが出がちです。

  • クライアントから預かった未公開画像を、外部のオンライン変換サイトにアップロードしたくない
  • 毎回コマンドライン(cwebp や ImageMagick)を叩くのが手間
  • サーバー側に画像変換APIを立てるとインフラ費用や運用負荷がかかる

実はモダンブラウザの Canvas API と HTMLCanvasElement.toBlob() を組み合わせれば、外部ライブラリなし・サーバー送信ゼロで複数枚の画像をWebPへ一括変換できます。

この記事では、そのまま実務に組み込める最小実装と、運用時にハマりやすい注意点(画質目安・透過維持・メモリ解放)をまとめます。


1. 最小の変換関数(1枚のFileをWebPのBlobへ変換)

基本の流れはシンプルです。

  1. 選択された File を画像としてデコードする(createImageBitmap)
  2. Canvasへ描画する(必要なら最大幅でリサイズ)
  3. canvas.toBlob(callback, 'image/webp', quality) でWebP形式の Blob を生成する
/**
 * 画像FileをWebP形式のBlobに変換する(ブラウザ内完結)
 * @param {File} file - 入力画像ファイル(PNG / JPEG等)
 * @param {object} options
 * @param {number} options.quality - 圧縮品質 (0.0 〜 1.0)
 * @param {number|null} options.maxWidth - 最大幅(リサイズ不要ならnull)
 * @returns {Promise<{ blob: Blob, width: number, height: number }>}
 */
async function convertFileToWebP(file, { quality = 0.82, maxWidth = null } = {}) {
  // 画像をデコード(EXIFの向き補正もモダンブラウザでは自動で反映される)
  const bitmap = await createImageBitmap(file);

  let targetW = bitmap.width;
  let targetH = bitmap.height;

  // 最大幅が指定されていて、元画像がそれを超える場合のみ縮小
  if (maxWidth && targetW > maxWidth) {
    const ratio = maxWidth / targetW;
    targetW = Math.round(targetW * ratio);
    targetH = Math.round(targetH * ratio);
  }

  const canvas = document.createElement('canvas');
  canvas.width = targetW;
  canvas.height = targetH;

  const ctx = canvas.getContext('2d');
  // 背景を塗りつぶさないことで、透過PNGのアルファチャンネルをそのまま維持できる
  ctx.drawImage(bitmap, 0, 0, targetW, targetH);

  // ImageBitmapは明示的に解放しておく(大量変換時のメモリ圧迫防止)
  bitmap.close();

  const blob = await new Promise((resolve, reject) => {
    canvas.toBlob(
      (result) => {
        if (!result) {
          reject(new Error('WebPへの変換に失敗しました'));
          return;
        }
        resolve(result);
      },
      'image/webp',
      quality
    );
  });

  // Canvasバッファを解放
  canvas.width = 0;
  canvas.height = 0;

  return { blob, width: targetW, height: targetH };
}

2. 複数ファイルの一括変換+削減率計算の実装例

実務で使う場合は、複数ファイルをまとめて処理し、**「何%軽くなったか」**を確認できると便利です。

大量の画像を Promise.all() で一気に並列処理するとブラウザのメモリを急激に消費してタブが落ちることがあるため、for ... of で1枚ずつ直列処理するのが安定します。

<input id="fileInput" type="file" accept="image/png,image/jpeg" multiple />
<ul id="resultList"></ul>

<script>
const fileInput = document.getElementById('fileInput');
const resultList = document.getElementById('resultList');

fileInput.addEventListener('change', async (e) => {
  const files = Array.from(e.target.files || []);
  resultList.innerHTML = '';

  for (const file of files) {
    try {
      const { blob, width, height } = await convertFileToWebP(file, {
        quality: 0.82,
        maxWidth: 1600,
      });

      const webpName = file.name.replace(/\.[^.]+$/, '') + '.webp';
      const reduction = Math.round((1 - blob.size / file.size) * 100);

      // ダウンロードリンクを生成
      const url = URL.createObjectURL(blob);
      const li = document.createElement('li');
      const a = document.createElement('a');
      a.href = url;
      a.download = webpName;
      a.textContent = `${webpName} (${width}x${height} /${(blob.size / 1024).toFixed(1)}KB / ${reduction}\%削減)`;  // クリック後にObjectURLを解放する場合は適宜 revokeObjectURL を呼ぶ li.appendChild(a); resultList.appendChild(li); } catch (err) { console.error(`${file.name} の変換に失敗:`, err);
    }
  }
});
</script>

3. 実務でハマりやすい4つの注意点

① quality の目安は用途別に分ける

toBlob('image/webp', quality) の第3引数(0.0〜1.0)は、高すぎると逆に元のJPEGより容量が増えることがあります。

画像のタイプ おすすめ quality 理由
写真・風景・商品画像 0.80 〜 0.85 見た目の劣化をほぼ感じずに大幅な軽量化が可能
図解・UIスクショ・文字多め 0.85 〜 0.92 低すぎると文字の輪郭にモスキートノイズが出やすい
サムネイル・一覧用の小画像 0.75 〜 0.80 表示サイズが小さいため圧縮率を優先しやすい

② 透過PNGの透明度を保つコツ

ctx.fillRect() で背景を塗りつぶさず、生成直後の透明なCanvasにそのまま drawImage() すれば、WebP変換後も透過情報が維持されます。

③ 大量変換時のメモリリーク対策

数十枚〜100枚を一括変換すると、以下の3つを解放し忘れただけでブラウザが重くなります。

  1. bitmap.close() で ImageBitmap を即座に解放する
  2. 変換後に canvas.width = 0; canvas.height = 0; で内部バッファを解放する
  3. プレビューやダウンロード用に作った URL.createObjectURL(blob) は不要になったタイミングで URL.revokeObjectURL(url) を呼ぶ

④ 元のファイルより大きくなるケースへの配慮

すでに高度に圧縮された小さなJPEGや色数の少ないPNGを再エンコードすると、WebPの方がサイズが大きくなる場合があります。実務ツールに組み込む際は、blob.size >= file.size のときに警告表示を出すか、品質を少し下げて再試行できるUIにすると親切です。


コードを書かずに今すぐ試したい場合

「仕組みは分かったけれど、普段のサイト制作ですぐ使える画面が欲しい」という場合は、今回紹介したようなブラウザ内完結の仕組みで動かしている無料Webツール一覧ページを公開しています。


まとめ

  • createImageBitmap + canvas.toBlob('image/webp', quality) だけで、サーバー不要のWebP一括変換が実装できる
  • 大量枚数を扱うときは Promise.all ではなく直列処理+リソース明示解放(bitmap.close() / revokeObjectURL)が安定する
  • 写真系は 0.80〜0.85、文字・図解系は 0.85〜0.92 を基準にすると画質と軽量化のバランスが取りやすい

静的サイトやクライアント案件の画像軽量化フローを自動化したいときの参考になれば幸いです。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?