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?

指定したフォルダ配下の jpg / png を一斉に webp 化(cwebp を使う)

0
Posted at

概要

webページ内で、 jpg / png 画像を読み込みしていますが、より圧縮率の高い WebP(ウェッピー) にすることで、高画質のままファイルサイズを大幅に軽量化することが期待できます。

ただ、一つ一つやってくのは面倒なので、cwebp という CUI を使って大量の画像を処理してしまおうという話。

cwebp の公式

このコマンドで何が起きるか簡単な説明

  • 指定したフォルダ配下の png や jpg (jpeg も含む) を一括で webp に変換し、変換が成功した場合のみ元の画像を削除する

コマンドの解説

  • find . -type f ...: 現在のディレクトリ (.) 以下のサブディレクトリも含めて、.jpg、.jpeg、.png ファイルを大文字・小文字問わず(-iname)すべて探し出す
  • | while read file; do ~ done: 見つかったファイルを1つずつ変数 file に入れて、中の処理を実行する
  • cwebp -q 85 "$file" -o "${file%.}.webp": cwebp で画質 85 (標準的なおすすめ値)で変換をします。${file%.}.webp は「元のファイルの拡張子を取り除いて .webp をつける」という指定
  • && rm "$file": 「&&」が非常に重要です。これは「左側のコマンド(cwebpの変換処理)が成功した場合だけ、右側のコマンドを実行する」という意味。万が一変換に失敗した際は元のファイルが削除されずに残る

コマンド

terminal などで、対象のフォルダに cd してから実行してください。

find . -type f \( -iname "*.jpg" -o -iname "*.jpeg" -o -iname "*.png" \) | while read file; do
  # 画質85でWebPに変換
  cwebp -q 85 "$file" -o "${file%.*}.webp" && rm "$file"
done

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?