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?

ImageMagick で WebP / AVIF をまとめて JPG に変換するワンライナー

0
Posted at

ImageMagick で WebP / AVIF をまとめて JPG に変換するワンライナー

WebP や AVIF で配布された画像を、JPG しか受け付けないツールに渡したい——そんなときに使える ImageMagick のワンライナーをまとめました。コピペで動きます。

前提

  • ImageMagick 7 系を想定しています(コマンドは magick)。
  • 6 系の方は、以下の magick をすべて convert に読み替えてください。
  • バージョンは magick -version で確認できます。

基本:カレントディレクトリの WebP / AVIF を一括変換

for f in *.webp *.avif; do magick "$f" "${f%.*}.jpg"; done

${f%.*} は拡張子を除いたファイル名を取り出す Bash のパラメータ展開です。photo.webp → photo.jpg のように変換されます。

片方の拡張子しか無いとき(glob のエラー対策)

たとえば .avif が 1 つも無いディレクトリで上のコマンドを実行すると、マッチしなかった *.avif がそのまま文字列として magick に渡され、エラーになります。

これを防ぐには nullglob を有効にして、マッチしない glob を空に展開させます。

shopt -s nullglob; for f in *.webp *.avif; do magick "$f" "${f%.*}.jpg"; done

サブディレクトリも含めて再帰的に変換

find を使えば、深い階層のファイルや大文字拡張子(.WEBP など)もまとめて拾えます。

find . -type f \( -iname '*.webp' -o -iname '*.avif' \) \
  -exec sh -c 'magick "$0" "${0%.*}.jpg"' {} \;

-iname は大文字小文字を区別しないので、.WebP のような表記も対象になります。

画質を指定したい

JPG の品質は -quality で調整できます(0〜100、デフォルトは保存形式依存)。

for f in *.webp *.avif; do magick "$f" -quality 90 "${f%.*}.jpg"; done

おまけ:変換前に件数を確認する

いきなり変換するのが不安なら、対象ファイルを先に数えておくと安心です。

ls *.webp *.avif 2>/dev/null | wc -l

まとめ

やりたいこと コマンド
カレントだけ一括変換 for f in *.webp *.avif; do magick "$f" "${f%.*}.jpg"; done
glob エラーを防ぐ 先頭に shopt -s nullglob;
再帰的に変換 find . -type f \( -iname '*.webp' -o -iname '*.avif' \) -exec ...
画質指定 -quality 90 を追加

用途に合わせて使い分けてみてください。

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?