I have converted png / jpeg for web page.

Environments

  • pngcrush-1.8.13
  • jpegtran-9b(17-Jan-2016)
  • macOS Catalina 10.15.6

Install

$ brew install pngcrush

,

$ brew install jpeg

and

$ brew install webp

Directory

.
└── static
    ├── original
    ├── img
    └── webp
  • The original images are saved in original
  • The converted images are saved in img
  • The webp images are saved in webp

MyCode

convert.sh

#!/bin/bash

cd ./static/original/
for file in *.png
do
  echo '# Convert png file ' ${file} 
  pngcrush -rem alla -brute -reduce ${file} ../img/${file}
done

for file in {*.jpg,*.jpeg}
do
  echo '# Convert jpeg file ' ${file} 
  jpegtran -copy none -optimize -perfect -outfile ${file} ../img/${file}
done

for file in {*.png,*.jpg}
do
  cwebp "$file" -o "../webp/${file%.*}.webp"
done

cd ../../
echo Remove original files
rm ./static/original/*

HTML Tag

I use picture tag

<picture>
  <source media="(max-width: 575.98px)" type="image/webp" srcset="/webp/mizuki-sp.webp" />
  <source media="(max-width: 575.98px)" srcset="/img/mizuki-sp.png" />
  <source type="image/webp" srcset="/webp/mizuki.webp" />
  <img decoding="async" class="image" alt="My Image" :src="'/img/mizuki.png'" />
</picture>

ToDo

I should try to use mozjpeg
Fix a bug. If input file name contains space(), it dose not work correctly.

# Convert jpeg file  filename with space.jpg
jpegtran: only one input file
usage: jpegtran [switches] [inputfile]
Switches (names may be abbreviated):
  -copy none     Copy no extra markers from source file
  -copy comments Copy only comment markers (default)
  -copy all      Copy all extra markers
  -optimize      Optimize Huffman table (smaller file, but slow compression)
  -progressive   Create progressive JPEG file
Switches for modifying the image:
  -crop WxH+X+Y  Crop to a rectangular subarea
  -flip [horizontal|vertical]  Mirror image (left-right or top-bottom)
  -grayscale     Reduce to grayscale (omit color data)
  -perfect       Fail if there is non-transformable edge blocks
  -rotate [90|180|270]         Rotate image (degrees clockwise)
  -scale M/N     Scale output image by fraction M/N, eg, 1/8
  -transpose     Transpose image

Ref

Pngcrush
pngcrush Homebrew
jpegtran
Webp webp Homebrew picture tag