category

Mixhost で画像を WebP に変換する

2020-07-10

昨日の続き。

2020-07-09

他の画像も WebP にしておこうと思ったので、今回も宮永さんのエントリを参考にさせてもらった。

3ファイルでできるサイト全体の自動的なWebP対応 - Qiita
https://qiita.com/miyanaga/ite...

感謝感謝。。。m(__)m

WebP に変換してくれる cwebp コマンドを使ってみる。

Precompiled Utilities | WebP | Google Developers
https://developers.google.com/...

最新版 libwebp-1.1.0-linux-x86-64.tar.gz (2020-07-10時点)を

https://storage.googleapis.com/downloads.webmproject.org/releases/webp/index.html

からダウンロードする。

設置場所は任意っぽいけど /home/hogehoge/bin/cwebp こんな感じで設置してパーミッションを 755 にする。

変換スクリプト、 .htaccess はそのまま使わせてもらいましたm(__)m

変換スクリプト webp.sh

#!/bin/bash

DIR="./images" # 対象ディレクトリパス(要変更)
JPEG_CWEBP_OPTS="-q 75 -m 4" # Jpeg向け非可逆cwebpオプション
PNG_CWEBP_OPTS="-lossless" # PNG向け可逆cwebpオプション
CWEBP="/usr/local/bin/cwebp" # cwebpコマンドの場所

cd $(dirname $0)
shopt -s nocasematch

find $DIR -type f -regextype posix-extended -iregex ".*\.(jpe?g|png)$" -print0 | \
while IFS= read -r -d '' SRC; do
  WEBP="$SRC.webp"
  if [[ ! -e $WEBP || $SRC -nt $WEBP ]]; then
    if [[ $SRC =~ \.jpe?g$ ]]; then
      echo "Convert to lossy WebP: $SRC"
      "$CWEBP" $JPEG_CWEBP_OPTS "$SRC" -o "$WEBP"
    elif [[ $SRC =~ \.png$ ]]; then
      echo "Convert to lossless WebP: $SRC"
      "$CWEBP" $PNG_CWEBP_OPTS "$SRC" -o "$WEBP"
    fi
  fi
done

実行権限を付与する

chmod a+x /home/hogehoge/webp.sh

htaccess 

<IfModule mod_setenvif.c>
  SetEnvIf Request_URI "\.(jpe?g|png)$" _image_request
</IfModule>

<IfModule mod_rewrite.c>
  RewriteEngine On
  RewriteCond %{HTTP_ACCEPT} image/webp
  RewriteCond %{SCRIPT_FILENAME}.webp -f
  RewriteRule .(jpe?g|png)$ %{SCRIPT_FILENAME}.webp [T=image/webp]
</IfModule>

<IfModule mod_headers.c>
  Header append Vary Accept env=_image_request
</IfModule>

<IfModule mod_mime.c>
  AddType image/webp .webp
</IfModule>

これでがりっとこれまでのファイルを WebP に変換できた(と思う)。

cron は1日1回に設定してみた。あとはうまく動くかどうか。


加藤さんが紹介していた imgix を使って変換するというのもありかと思う。

だいぶ簡単に使えそうだなー。
既存サイトとかでも使いやすそう。

imgix を使えそうな Craft CMS のプラグインもいくつかありそう。

Glide も変換できそうな感じではあったけど。

今回は一旦見送り。