Skip to content

Instantly share code, notes, and snippets.

@DerekBuntin
Last active August 26, 2024 05:44
Show Gist options
  • Save DerekBuntin/a5abd2524f1bb46f4057c85009515015 to your computer and use it in GitHub Desktop.
Save DerekBuntin/a5abd2524f1bb46f4057c85009515015 to your computer and use it in GitHub Desktop.
Find all images within a folder and recursively convert to webp and resize.
#!/bin/bash
# Define the main images folder
main_images_folder="images"
# Define the desired width for the images
target_width=738
# Find and process all image files recursively
find "${main_images_folder}" -type f \( -iname "*.jpg" -o -iname "*.jpeg" -o -iname "*.png" -o -iname "*.gif" -o -iname "*.tif" -o -iname "*.tiff" -o -iname "*.bmp" -o -iname "*.webp" \) | while read file; do
# Get the base name without extension
base_name=$(basename "${file%.*}")
# Get the directory of the current file
dir_name=$(dirname "$file")
# Create the target sub-directory inside 'list' if it doesn't exist
mkdir -p "${dir_name}/list"
# Check if the file is already a webp
if [[ "$file" == *.webp ]]; then
# Resize the webp image to target width with the aspect ratio maintained
magick "$file" -resize "${target_width}" "${dir_name}/list/${base_name}.webp"
else
# Convert and resize the image to target width with the aspect ratio maintained
magick "$file" -resize "${target_width}" "${dir_name}/list/${base_name}.webp"
fi
done
@DerekBuntin
Copy link
Author

DerekBuntin commented Aug 26, 2024

Steps to Run the Script:

Create the Shell Script (.sh) File:

  1. Open Terminal.
  2. Navigate to a Directory: cd ~/Desktop
  3. Create the Script File: nano process_images_recursive.sh
  4. Paste the Script: Copy the updated script and paste it into nano. In nano, you can paste by right-clicking or using Command + V.
  5. Save and Exit: In nano, save the file with Control + O, press Enter to confirm, then exit nano with Control + X.
  6. Make the Script Executable: chmod +x process_images_recursive.sh
  7. Run the Script: ./process_images_recursive.sh

Here’s how this might look in a terminal session:

Navigate to the Desktop
cd ~/Desktop

Create the script file
nano process_images_recursive.sh

Paste the script content into nano(Use Command + V to paste, or right-click)

Save and exit nano (Control + O, Enter, then Control + X)

Make the script executable
chmod +x process_images_recursive.sh

Run the script
./process_images_recursive.sh

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment