How to batch resize images in Ubuntu recursively within the terminal?

前端 未结 6 1376
栀梦
栀梦 2020-12-23 10:15

I have multiple images stored in a set of organized folders. I need to re-size those images to a specific percentage recursively from their parent directory

6条回答
  •  眼角桃花
    2020-12-23 10:42

    there are a few answers like:

    find . -name "*.jpg" | xargs convert -resize 50%
    

    this won't work as it will expand the list like this: convert -resize 50% a.jpg b.jpg c.jpg which will resize a.jpg in c-0.jpg, b.jpg in c-1.jpg and let c.jpg untouched.

    So you have to execute the resize command for each match, and give both input file name and output file name, with something like:

    find . -name "*.jpg" | xargs -n 1 sh -c 'convert -resize 50% $0 $(echo $0 | sed 's/\.jpg/-th\.jpg/')'
    

    each match of find is individually passed by xargs -n 1 to the resize script: sh -c 'convert -resize 50% $0 $(echo $0 | sed 's/\.jpg/-th\.jpg/')'. This script receives the file name in argument $0, uses sed to make an output file name by substitution of the original .jpg suffix by a -th.jpg one. And it runs the convert command with those two file names.

    Here is the version without xargs but find -exec:

    find -name '*.jpg' -exec sh -c 'convert -resize 50% $0 $(echo $0 | sed 's/\.jpg/-th\.jpg/')' {} \;
    

提交回复
热议问题