Menü schliessen
Created: March 6th 2024
Categories: Linux,  Wordpress
Author: LEXO

Linux Bash Script: Batch- Resize, Rescale- and Sharpen images inside of a given folder to reduce storage demand

Donation Section: Background
Monero Badge: QR-Code
Monero Badge: Logo Icon Donate with Monero Badge: Logo Text
82uymVXLkvVbB4c4JpTd1tYm1yj1cKPKR2wqmw3XF8YXKTmY7JrTriP4pVwp2EJYBnCFdXhLq4zfFA6ic7VAWCFX5wfQbCC

In the realm of digital imagery, size (and sharpness) truly matters! Whether you're a digital artist tired of your masterpieces hogging all the disk space, a photographer looking to batch-process a gazillion photos from your last adventure, or just a regular Joe trying to send a bunch of vacation pics without crashing your email, I've got a spell-binding solution for you. Introducing the Ultimate Bash Script for Resizing and Sharpening Your Images – a must-have tool for every Linux wizard out there!

The Enchantment Behind the Script

Before we dive into the arcane arts of bash scripting, let's set the stage. Imagine you've got a folder brimming with images. Beautiful, high-resolution images that are... well, frankly, unnecessarily huge. What if I told you that you could magically transform them into web-friendly versions without sacrificing quality? Enter our bash script, a potent concoction brewed in the cauldron of command-line utilities, ready to resize and recompress your images with the finesse of a Michelin-star chef garnishing a plate.

What This Sorcery Does

Our script is no ordinary spell. It's the Gandalf of image processing in the realm of Linux. Here's what it promises:

  • Selective Resizing: Like a discerning bouncer at an exclusive club, it only resizes images that exceed a certain resolution threshold you define. Because not all images need to slim down.
  • Quality Recompression: It uses the alchemical powers of ImageMagick to ensure your images are recompressed without turning into pixel porridge.
  • Unsharp Masking: It sharpens your images with the precision of a samurai's katana, thanks to a clever unsharp mask filter. No more blurry pics!

How It Works: A Spellbook Revealed

Without further ado, let's reveal the incantations. But be warned, for great power comes great responsibility (and possibly a need for more disk space).

Ingredients

  1. A Linux system, preferably not cursed.
  2. ImageMagick installed, not by magic but by a simple sudo apt-get install imagemagick (or your distro's equivalent).

The Spell:

Hint: Check out the variable QUALITY=70 in the code. This is the JPG compression quality level. Maybe you want to change that.

resize_and_sharpen.sh

#!/bin/bash

# Check for folder argument
if [ $# -eq 0 ]; then
    echo "Error: No folder path provided."
    exit 1
fi

FOLDER_PATH=$1

# Ensure ImageMagick is installed
if ! command -v convert &> /dev/null; then
    echo "ImageMagick (convert) is not found, please install it and try again."
    exit 1
fi

# Warning about file overwrite
echo -e "This process will overwrite original files. Do you want to continue? (y/n)"
read -r CONTINUE
if [[ "$CONTINUE" != "y" ]]; then
    echo "Process aborted."
    exit 1
fi

# Ask for desired resolution
echo "Please enter the desired horizontal resolution (e.g., 1920):"
read -r TARGET_RESOLUTION

# Start processing
echo "Starting process..."

# Find images and count them
IMAGES=($(find ${FOLDER_PATH} -type f \( -iname "*.jpg" -o -iname "*.jpeg" -o -iname "*.png" \)))
TOTAL_IMAGES=${#IMAGES[@]}
echo "Building a list of all images: $TOTAL_IMAGES images found."

# Variables to hold size calculations
TOTAL_ORIGINAL_SIZE=0
TOTAL_NEW_SIZE=0

echo "Starting image resizing and converting process..."

for i in "${!IMAGES[@]}"; do
    FILE="${IMAGES[$i]}"
    ORIGINAL_SIZE=$(du -b "$FILE" | cut -f1)
    TOTAL_ORIGINAL_SIZE=$((TOTAL_ORIGINAL_SIZE + ORIGINAL_SIZE))

    # Get image width
    WIDTH=$(identify -format "%w" "$FILE")

    # Determine quality based on file extension
    ext="${FILE##*.}"
    if [[ "${ext,,}" == "jpg" || "${ext,,}" == "jpeg" ]]; then
        QUALITY=70
    else
        QUALITY=100
    fi

    # Resize images that are larger than the target resolution
    # Recompress all images maintaining their original resolution if smaller than the target
    if [ "$WIDTH" -gt "$TARGET_RESOLUTION" ]; then
        convert "$FILE" -filter Lanczos -resize "${TARGET_RESOLUTION}" -quality $QUALITY -unsharp 0x2+1.0+0.02 "$FILE"
    else
        convert "$FILE" -filter Lanczos -resize "${WIDTH}" -quality $QUALITY -unsharp 0x2+1.0+0.02 "$FILE"
    fi

    NEW_SIZE=$(du -b "$FILE" | cut -f1)
    TOTAL_NEW_SIZE=$((TOTAL_NEW_SIZE + NEW_SIZE))
    echo -e "$((i + 1)) / $TOTAL_IMAGES: $FILE | Original Size: $(echo "scale=2; $ORIGINAL_SIZE/1024/1024" | bc) MB | New Size: $(echo "scale=2; $NEW_SIZE/1024/1024" | bc) MB"
done

echo "Process finished."
echo "Total Sizes: Original: $(echo "scale=2; $TOTAL_ORIGINAL_SIZE/1024/1024" | bc) MB | New: $(echo "scale=2; $TOTAL_NEW_SIZE/1024/1024" | bc) MB"

This powerful script takes a folder path as an offering and embarks on a quest to find all JPG, JPEG, and PNG images. It then consults the oracle (you) for a desired resolution. Images daring to exceed this resolution are resized and sharpened, while the smaller ones are merely polished to perfection with the same sharpening charm, ensuring consistency across your digital realm.

Cast the Spell: A Wizard's Guide

To unleash the power of this script, simply invoke it from your terminal, like so:

./resize_and_sharpen.sh /path/to/your/image/folder

But beware! This spell is potent and irreversible. Once cast, it will overwrite your original images with their new, enhanced forms. Fear not, for the script kindly asks for your permission before proceeding. A courteous wizard is a wise wizard.

The Alchemy of ImageMagick

At the heart of this spell lies ImageMagick, the Swiss Army knife of image processing. It's like having Dumbledore, Gandalf, and Merlin in your toolkit, ready to tackle any image manipulation task you throw at it.

  • Lanczos Filter: This isn't just any filter. It's the crème de la crème of resizing filters, ensuring your images lose weight without losing their charm.
  • Unsharp Masking: Ever wondered how to make your images sharper than a vampire's fang? The unsharp mask is your answer, adding just the right amount of edge to your pictures without overdoing it.

The Ritual of Installation

Should you find your toolkit lacking ImageMagick, fear not. Installing it is as simple as reciting the ancient spell:

sudo apt-get install imagemagick

Or, for those who hail from the lands of Fedora or CentOS:

sudo yum install imagemagick

A Word of Caution

Before you embark on this magical journey, let me impart some wizardly advice:

  • Backup Your Images: Always have a copy of your images stored in a dragon-proof vault (or just another folder).
  • Experiment Wisely: The settings provided are but a starting point. Feel free to tweak the unsharp mask parameters to suit your images. Not all spells work the same on every subject.

In Conclusion: Your New Powers

Armed with this script, you're now equipped to tackle the digital world's most daunting challenge: managing a vast image collection without compromising on quality. So go forth, resize, recompress, and sharpen with confidence!

Remember, with great power comes a great need to read the manual. But who needs manuals