Resize multiple images proportionally with FFmpeg and a shell function
December 26, 2021 ≈ 2 minutes 6 seconds
You probably already know that FFmpeg can resize images proportionally, and also that it can't overwrite them. So you either save resized files under new names or into a new folder, and it becomes tedious... When you repeat the same pattern multiple times over the week, it's time to search for a way to automate it.
So I wrote that little shell function for myself and I share it with the hope that it helps you too (you can include it into your .aliases file). I included comments for better understanding.
# resize_images -w400 -h800 -tpng
# resize_images -h800 -tjpg
function resize_images()
{
width='-1'; height='-1'; type=''; # -1 if we scale proportionally in ffmpeg
folder="tmp_$(date +%s)"; # tmp_ + timestamp
files_count=0; resized_files_count=0; # count of files in folder and tmp_ folder
# read width, height and type
while getopts "w:h:t:" opt; do # w - width, h - height, t - type, : - expect value
case ${opt} in
w ) width=${OPTARG} ;;
h ) height=${OPTARG} ;;
t ) type=${OPTARG} ;;
esac
done
if [[ $type == '' ]]; then # type can't be empty
echo "No image file type provided. Example: resize_images -w100 -h50 -tpng"; return;
fi
if [[ $width == '-1' && $height == '-1' ]]; then # either width or height should be provided
echo "No width or height provided. Example: resize_images -w100 -tpng "; return;
fi
files_count=$(ls *.$type | wc -l | tr -d ' ') # count all files of type in current folder
if [[ $files_count == 0 ]]; then # should be at least one file of type
echo "No $type files in a folder"; return;
fi
mkdir $folder # create temporary folder: tmp_ + timestamp
# resize files and save in temporary folder
for i in *.$type ; do ffmpeg -i "$i" -vf scale="$width:$height" "$folder/$i" ; done
resized_files_count=$(ls $folder/*.$type | wc -l | tr -d ' ') # count files of type in temporary folder
# if count of files in current folder different from count of files in temporary, display error
if [[ $files_count != $resized_files_count ]]; then
echo "Error while resizing: files count mismatch"; return;
fi
# Promt confirmaiton
echo "Do you want to rewrite original files with files from $folder (y/n)?"
read -q choice # read answer in choice variable
if [[ $choice != 'y' ]] return
rm *.$type # Remove all files of type from current folder
mv ./$folder/*.$type . # Move all files from temporary to the current folder
rm -rf $folder # Remove temporary folder
}
You didn't provide any data, entered invalid email or already subscribed.
Try again. And if you still can't subscribe—write us.
Address successfully subscribed!
Subscribe to our newsletter
If you provide url of your website, we send you free design concept of one element (by our choice)
Subscribing to our newsletter, you comply with subscription terms and Privacy Policy