Skip to content

Instantly share code, notes, and snippets.

@tvinhpham
Created July 18, 2024 03:21
Show Gist options
  • Save tvinhpham/772fe4cf914e894dca962525711c406f to your computer and use it in GitHub Desktop.
Save tvinhpham/772fe4cf914e894dca962525711c406f to your computer and use it in GitHub Desktop.
Common tools to resize images & video converter
#!/bin/bash
#REQUIREMENTS
# - ffmpeg
# - magick
mov_2_mp4() {
if [ -z $1 ]; then
echo "Please enter source file"
return 1
fi
file=$1
extension="${file##*.}"
filename="${file%.*}"
if [ $extension != "mov" ]; then
echo "Not supported"
return 1
fi
ffmpeg -i $file -vcodec h264 -acodec mp2 $filename.mp4
}
2webm() {
if [ -z $1 ]; then
echo "Please enter source file"
return 1
fi
file=$1
extension="${file##*.}"
filename="${file%.*}"
if [ $extension != "mov" ] && [ $extension != "mp4" ]; then
echo "Not supported"
return 1
fi
ffmpeg -i $file -c:v libvpx -crf 15 -b:v 1M -c:a libvorbis $filename.webm
}
2webp() {
if [ -z $1 ]; then
echo "Please enter source file"
return 1
fi
file=$1
extension="${file##*.}"
filename="${file%.*}"
if [ $extension != "png" ] && [ $extension != "jpeg" ] && [ $extension != "jpg" ]; then
echo "Not supported"
return 1
fi
echo "Please wait"
magick $file $filename.webp
}
function resize_images() {
delete_originals=false
if [ "$1" = "-d" ]; then
delete_originals=true
shift
fi
dir="$1"
for img in "$dir"/*.jpg; do
if [ -f "$img" ]; then
# Get the image dimensions using exiftool
local width=$(exiftool -s3 -ImageWidth "$img")
local height=$(exiftool -s3 -ImageHeight "$img")
# Determine the longest edge
if [ "$width" -gt "$height" ]; then
local longest_edge=$width
else
local longest_edge=$height
fi
# Check if the longest edge is greater than 2048 pixels
if [ "$longest_edge" -gt 2048 ]; then
# Resize the image to 2048 pixels on the longest edge while preserving the aspect ratio
local new_filename="$dir/HD-${img##*/}"
ffmpeg -i "$img" -vf "scale='if(gt(iw,ih),2048,-1)':'if(gt(iw,ih),-1,2048)':flags=lanczos" -q:v 0 -c:a copy -metadata:s:v:0 dpi=72 "$new_filename"
# Copy the EXIF data from the original image to the resized image
exiftool -TagsFromFile "$img" "-all:all>all:all" -overwrite_original "$new_filename"
# Delete the original file if the delete flag is set
if $delete_originals; then
rm "$img"
fi
fi
fi
done
# Process nested directories
for dir in "$1"/*/; do
if [ -d "$dir" ]; then
if $delete_originals; then
resize_images -d "$dir"
else
resize_images "$dir"
fi
fi
done
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment