I have a list of .JPG files on a Mac. I want to export them to a format taking less than 500 kilobytes per image. I know how to do that using the Preview application one image at a time; but I want to be able to do the same in batch, meaning on several files at once. Is there a command line way to do it so I could write a script and run it in the terminal? Or some other way that I could use?
This is an example from the command line using convert (brew info imagemagick
) converting all *.jpg
images in one directory to .png
:
for i in *.jpg; do
convert "$i" "${i%.jpg}.png"
done
For a dry run (test) you can use echo
instead of the <command>
:
for i in *.jpg; do
echo "$i" "${i%.jpg}.png"
done
This will search for files within the directory having the extension .jpg
then execute the command convert
, passing as arguments the file name $i
and then using as an output the same file name removing the extension and adding the new one .png
. This is done using:
"${i%.jpg}.png"
Double quotes "
are used in case the filename contains spaces. Documentation for shell parameter expansion (search the docs for ${parameter%word}
).
For example, to just change the quality of the file you could use:
convert "$i" -quality 80% "${i%.jpg}-new.jpg"
Or if no need to keep the original:
mogrify -quality 80% *.jpg
The main difference is that ‘convert‘ tends to be for working on individual images, whereas ‘mogrify‘ is for batch processing multiple files.