The convert program will convert a file from one image format to another:
$ convert INPUT_FILE OUTPUT_FILE
Here's an example of this:
$ convert file1.jpg file1.png
We can resize an image by specifying the scale percentage or the width and height of the output image. To resize an image by specifying WIDTH or HEIGHT, use this:
$ convert imageOrig.png -resize WIDTHxHEIGHT imageResized.png
Here's an example of this:
$ convert photo.png -resize 1024x768 wallpaper.png
If either WIDTH or HEIGHT is missing, then whatever is missing will be automatically calculated to preserve the image aspect ratio:
$ convert image.png -resize WIDTHx image.png
Here's an example of this:
$ convert image.png -resize 1024x image.png
To resize the image by specifying the percentage scale factor, use this:
$ convert image.png -resize "50%" image.png
This script will perform a set of operations on all the images in a directory:
#!/bin/bash
#Filename: image_help.sh
#Description: A script for image management
if [ $# -ne 4 -a $# -ne 6 -a $# -ne 8 ];
then
echo Incorrect number of arguments
exit 2
fi
while [ $# -ne 0 ];
do
case $1 in
-source) shift; source_dir=$1 ; shift ;;
-scale) shift; scale=$1 ; shift ;;
-percent) shift; percent=$1 ; shift ;;
-dest) shift ; dest_dir=$1 ; shift ;;
-ext) shift ; ext=$1 ; shift ;;
*) echo Wrong parameters; exit 2 ;;
esac;
done
for img in `echo $source_dir/*` ;
do
source_file=$img
if [[ -n $ext ]];
then
dest_file=${img%.*}.$ext
else
dest_file=$img
fi
if [[ -n $dest_dir ]];
then
dest_file=${dest_file##*/}
dest_file="$dest_dir/$dest_file"
fi
if [[ -n $scale ]];
then
PARAM="-resize $scale"
elif [[ -n $percent ]]; then
PARAM="-resize $percent%"
fi
echo Processing file : $source_file
convert $source_file $PARAM $dest_file
done
The following example scales the images in the sample_dir directory to 20%:
$ ./image_help.sh -source sample_dir -percent 20% Processing file :sample/IMG_4455.JPG Processing file :sample/IMG_4456.JPG Processing file :sample/IMG_4457.JPG Processing file :sample/IMG_4458.JPG
To scale images to a width of 1024, use this:
$ ./image_help.sh -source sample_dir -scale 1024x
To scale and convert files into a specified destination directory, use this:
# newdir is the new destination directory $ ./image_help.sh -source sample -scale 50% -ext png -dest newdir