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?

ディレクトリ配下の画像を一括でwebpに変換する(cwebp)

Last updated at Posted at 2025-03-12

この記事は、ホームページやWebアプリの読み込み速度が遅い!という時に、使えるかもしれない内容になります。
実際この方法を使って、4.7MB程の画像を目視劣化なしで280KBほどに圧縮(圧縮率95%程)することが出来ました。

cwebp(libwebp)とは

cwebp は、Google が開発した WebP 画像フォーマット用のエンコーダーで、libwebp(WebP のライブラリ)に含まれる コマンドラインのツール です。

JPEG, PNG, TIFF, BMP などの画像を webp に変換することが可能です。

また、画質、圧縮率、アルファチャンネルの設定も行えます。

cwebp(libwebp)のインストール

# Ubuntu
sudo apt install webp  

# macOS(Homebrew)
brew install webp

# Windows(Chocolatey)
choco install webp

使い方

単体で変換を行う場合は、以下のように使用します。

cwebp "変換前ファイル名" -o "変換後ファイル名.webp"

webpへの一括変換

以下のスクリプトは、
元のファイルを削除しつつ、ディレクトリ配下の.jpg.pngを全て.webpへ一括変換します。

macOS / Ubuntu

find . -type f \( -iname "*.jpg" -o -iname "*.png" \) -exec sh -c '
for file do
    cwebp "$file" -o "${file%.*}.webp"
    rm "$file" # 元のファイルを削除したくない場合は、この行をコメントアウトしてください。
done
' sh {} +

Windows

$extensions = @("*.jpg", "*.png")

foreach ($ext in $extensions) {
    Get-ChildItem -Path . -Recurse -Filter $ext | ForEach-Object {
        $webpFile = $_.FullName -replace "\.(jpg|png)$", ".webp"
        Start-Process -NoNewWindow -Wait -FilePath "cwebp" -ArgumentList "`"$($_.FullName)`" -o `"$webpFile`""
        Remove-Item $_.FullName  # 元のファイルを削除したくない場合は、この行をコメントアウト
    }
}
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?