1

I have a file with the full path to an image on each line, all are jpg. I want to resize every image/line in the file to 1024px in width, while keeping the aspect ratio for the height. I simply want to overwrite the original file.

The main thing I'm having issue with is, I want to SHRINK only. I do not want to enlarge images smaller than 1024px in width up to 1024px in width.

Here is the bash script I'm working with and just need help with the convert line as I have no experience with imagemagick.

#!/bin/bash

while read p; do
  convert $p
done < listofimages
0

2 Answers 2

2

This should do it:

#!/bin/bash

while IFS= read -r jpg
do
    convert "$jpg""[1024x>]" "$jpg"
done < "$1"

Save the script above as ~/bin/shrink.sh, make it executable (chmod a+x ~/bin/shrink.sh) and run it, giving the list of files as an argument:

shrink.sh /path/to/list

This is basically the same as the proposed duplicate, adapted to i) match your desired size and ii) read the names from a file. The [1024x>] ensures that only images whose size is greater than 1024 pixels will be resized.

1
  • Thanks. Yes, I did need the proposed duplicate adapted slightly. May 27, 2015 at 0:10
-1

Try something like this:

#!/bin/bash

for p in "$@"
do
    w=`identify "$p" | cut -f 3 -d ' ' | sed 's/x.*//'`
    if [ $w -gt 1024 ]
    then
        convert -scale 1024x1024 "$p" "$p"
    fi
done

Explanation:

  • The "identify" command produces all sorts of info about the image. The third field is the size, in the format "1024x968".
  • The "cut" command grabs the third field, delimited by spaces.
  • The "sed" command deletes the height, leaving the width.
  • The "if" only processes images whose width is larger than 1024.
  • Finally, convert rescales the image. It automatically keeps the aspect ratio.

If you've got file names in a file, and name the above script "reaspect", you can use this:

% reaspect `cat file`
4
  • 2
    The OP needs to read the image names from a file.
    – terdon
    May 26, 2015 at 17:44
  • Much better (and disregard my previous comment about reaspect, I should learn to read first). Your cut will still break if the file name contains whitespace though. Same with using cat file. You could get the right width by running identify "$w" | rev | cut -d ' ' -f 7 but the file names will still be an issue if you're using cat.
    – terdon
    May 26, 2015 at 18:06
  • Thanks for the constructive comments. I'm not understanding the "$jpg""[1024x>]" in your script. Could you add a bit of explanation? May 26, 2015 at 18:08
  • I found it in the answer to the duplicate. It is documented (slightly) here. Basically, it sets a threshold and images already smaller than that will not be touched.
    – terdon
    May 26, 2015 at 21:59

Not the answer you're looking for? Browse other questions tagged .