Skip to content

Instantly share code, notes, and snippets.

@emmadesilva
Created June 25, 2024 14:43
Show Gist options
  • Select an option

  • Save emmadesilva/cbbc88806223b6cec3d77239fc395e20 to your computer and use it in GitHub Desktop.

Select an option

Save emmadesilva/cbbc88806223b6cec3d77239fc395e20 to your computer and use it in GitHub Desktop.
Bash ImageMagick script to compress images in a directory named source to a directory called output
#!/bin/bash
# Ensure the output directory exists
mkdir -p output
# Iterate through all image files in the source directory
for image in source/*.{jpg,jpeg,png,gif}; do
if [[ -f "$image" ]]; then
# Get the filename without the directory path
filename=$(basename "$image")
# Print output
echo "converting $filename"
# Compress the image and save it to the output directory
convert "$image" -strip -interlace Plane -gaussian-blur 0.05 -quality 85% "output/$filename"
fi
done
echo "Image compression complete. Compressed images are saved in the 'output' directory."
@emmadesilva
Copy link
Author

emmadesilva commented Jun 25, 2024

Video version

#!/bin/bash

# Ensure the output directory exists
mkdir -p output

# Function to display progress bar
progress_bar() {
  local duration=$1
  local filename=$2

  echo -ne "Compressing $filename ["
  local elapsed=0
  while [[ $elapsed -lt $duration ]]; do
    local percent=$(( (elapsed * 100) / duration ))
    local bar=$(printf "%-${percent}s" "=")
    echo -ne "$bar\r"
    sleep 1
    ((elapsed++))
  done
  echo "] Done!"
}

# Iterate through all mp4 files in the source directory
for video in source/*.mp4; do
  if [[ -f "$video" ]]; then
    # Get the filename without the directory path
    filename=$(basename "$video")

    # Get the duration of the video in seconds
    duration=$(ffmpeg -i "$video" 2>&1 | grep "Duration" | awk '{print $2}' | tr -d , | awk -F: '{ print ($1 * 3600) + ($2 * 60) + $3 }')

    # Start the compression process in the background
    ffmpeg -i "$video" -vcodec libx265 -crf 28 "output/$filename" &

    # Get the process ID of the ffmpeg command
    ffmpeg_pid=$!

    # Display the progress bar
    progress_bar $duration "$filename" &

    # Wait for the ffmpeg process to complete
    wait $ffmpeg_pid

    echo "Compression of $filename completed."
  fi
done

echo "Video compression complete. Compressed videos are saved in the 'output' directory."

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