Reduce the size of images from the command line
One of the cool ways of reducing all the images in a folder is to use the following command:
find . -name '*.jpg' -type f -exec bash -c 'convert -resize 60% -quality 80 "$0" "${0%.jpg}-small.jpg" && echo "Converted : $0"' {} ;
Sure! Let's break down the bash code step by step.
-
find .: This command is used to search for files and directories starting from the current directory (.). -
-name '*.jpg': This restricts the search to files with the.jpgextension. The single quotes around*.jpgensure that the shell doesn't expand the wildcard (*), and instead it's passed tofindas a literal argument. -
-type f: This specifies that we are only interested in files, not directories. -
-exec ... ;: This option tellsfindto execute a specified command on each file that matches the criteria. The{}within the-execcommand gets replaced by the current file thatfindis processing. The;at the end (escaped with a space before it) indicates the end of the-execcommand. -
bash -c '...': This starts a new bash shell to execute the command provided in the single quotes. We're using a new bash shell because the commands within the quotes use bash-specific features. -
convert -resize 60% -quality 80 "$0" "${0%.jpg}-small.jpg": This uses theconvertcommand from the ImageMagick suite to process the image.-resize 60%: This resizes the image to 60% of its original size.-quality 80: This sets the JPEG quality to 80%."$0": This is the current file being processed (the same as{}from thefindcommand)."${0%.jpg}-small.jpg": This uses string manipulation to remove the.jpgextension from the filename and append-small.jpg. For example, if the file isimage.jpg, it would becomeimage-small.jpg.
-
&&: This is a logical operator. The command after the&&will only be executed if the command before it succeeded (i.e., returned a 0 exit status). -
echo "Converted : $0": If theconvertcommand succeeded, this will print a message indicating which file was converted.
In summary, this bash code will search for all .jpg files in the current directory and its subdirectories. For each .jpg file, it will create a resized version of the image with 60% of the original size and a quality of 80%, and it will append -small to the filename of the new image. If the conversion is successful for a particular file, it will print a message indicating which file was converted.