Skip to content

Instantly share code, notes, and snippets.

@lovasoa
Last active February 23, 2026 23:17
Show Gist options
  • Select an option

  • Save lovasoa/429d8b3909b86923833a4894fd1730a0 to your computer and use it in GitHub Desktop.

Select an option

Save lovasoa/429d8b3909b86923833a4894fd1730a0 to your computer and use it in GitHub Desktop.
#!/bin/bash
# Define source and output directories
SOURCE_DIR="$(pwd)"
OUTPUT_DIR="$SOURCE_DIR/recompressed"
# Create the output directory if it doesn't exist
mkdir -p "$OUTPUT_DIR"
echo "Starting batch processing..."
# Determine the ImageMagick command (newer versions use 'magick', older use 'convert')
IMAGEMAGICK_CMD=""
if command -v magick >/dev/null 2>&1; then
IMAGEMAGICK_CMD="magick"
elif command -v convert >/dev/null 2>&1; then
IMAGEMAGICK_CMD="convert"
else
echo "❌ Error: ImageMagick is not installed. Please install it (e.g., sudo dnf install ImageMagick)."
exit 1
fi
# Loop through all files in the source directory
for file in "$SOURCE_DIR"/*; do
# Skip directories and the script itself
if [ -d "$file" ]; then
continue
fi
# Extract filename and lowercase extension for matching
filename=$(basename "$file")
# Skip if the file has already been successfully processed
if [ -s "$OUTPUT_DIR/$filename" ]; then
echo "⏭️ Skipping already processed file: $filename"
continue
fi
extension="${filename##*.}"
extension_lower=$(echo "$extension" | tr '[:upper:]' '[:lower:]')
# Check if the file is a video
if [[ "$extension_lower" =~ ^(mp4|mov|mkv|avi|webm)$ ]]; then
echo "🎬 Re-encoding video: $filename"
ffmpeg -hide_banner -loglevel error -y -hwaccel vaapi -hwaccel_output_format vaapi -i "$file" -vf "hwupload,format=vaapi" -c:v hevc_vaapi -global_quality 40 -c:a copy "$OUTPUT_DIR/$filename"
# Check if the file is an image (excluding GIF as it can break animations)
elif [[ "$extension_lower" =~ ^(jpg|jpeg|png|webp)$ ]]; then
echo "🖼️ Compressing photo: $filename"
# '-quality 82' offers excellent visual quality with much smaller file sizes
"$IMAGEMAGICK_CMD" "$file" -quality 82 "$OUTPUT_DIR/$filename"
# Keep GIFs intact
elif [[ "$extension_lower" == "gif" ]]; then
echo "🖼️ Copying animated GIF (uncompressed): $filename"
cp "$file" "$OUTPUT_DIR/$filename"
else
echo "⚠️ Skipping unknown file type or script: $filename"
fi
done
echo "✅ Batch processing complete! Your files are in the 'recompressed' folder."
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment