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.

  1. find .: This command is used to search for files and directories starting from the current directory (.).

  2. -name '*.jpg': This restricts the search to files with the .jpg extension. The single quotes around *.jpg ensure that the shell doesn't expand the wildcard (*), and instead it's passed to find as a literal argument.

  3. -type f: This specifies that we are only interested in files, not directories.

  4. -exec ... ;: This option tells find to execute a specified command on each file that matches the criteria. The {} within the -exec command gets replaced by the current file that find is processing. The ; at the end (escaped with a space before it) indicates the end of the -exec command.

  5. 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.

  6. convert -resize 60% -quality 80 "$0" "${0%.jpg}-small.jpg": This uses the convert command 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 the find command).
    • "${0%.jpg}-small.jpg": This uses string manipulation to remove the .jpg extension from the filename and append -small.jpg. For example, if the file is image.jpg, it would become image-small.jpg.
  7. &&: 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).

  8. echo "Converted : $0": If the convert command 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.