Image compression using Pillowscript
Programmatic compression of images using existing algorithmscan be undertaken using a command-line script.
- Download the lossy_compression.py script to your device
- Move the script to a stable location, such as your userhome directory
- Make the script executable
chmod+x .../lossy_compression.py
- Install ImageMagick
brew install imagemagick
- Install Pillow
python3 -m pip install pillow
- Install Numba
python3 -m pip install numba
- Install NumPy
python3 -m pip install numpy
- Install openpyxl
python3 -m pip install openpyxl
To bulkresize all images in a directory, use Mac’s built-in sips tool. Navigate to the destination in Terminal and then run the followingscript:
sips -Z 1200 \*.jpg
*NB this script may inadvertently upscale images smallerthan the dimensions specified.
To avoid this, navigate to a top-level directory usingTerminal and use the following to search for all files that exceed thespecified dimension recursively, and then only apply the transformation tothose:
mogrify -resize '2000>' *.jpg
To bulk change the DPI of all images in a directory,navigate to the destination in Terminal and then run the following script:
find . -name "*.jpg" -exec mogrify -units "PixelsPerInch" -density 72\> {} \;
Output formats:
- JPEG
- PNG
- WebP
Dithering modes:
- one_bit
- bayer_2x2
- cluster_4x4
- bayer_8x8
- floyd_steinberg_pil
- atkinson
- stucki
- jarvis_judice_ninke
- grayscale
- floyd_stinberg_dev
python3 "SCRIPT LOCATION" "IMAGE DIRECTORY" "lossy_compression" "DITHERING MODE" "FORMAT"
The script will create a new directory at the same level asthe source in which to store the derivatives generated. Additionally, it willproduce a spreadsheet listing the files and their relative transformation sizes.