0

I want to reduce the size of my JPG images to the same total pixel size (e.g. 6MPx) no matter of the input size or ratio.


Of course mogrify or convert can resize:

This ...

mogrify -resize 3000x3000 file.jpg

... will give me 6MPx for pictures with ratio 3:2.

But this won't work with unusual ratios like e.g. panoramas.


Q: How to use mogrify / convert to get a specified target pixel size ?

1
  • Note, I already added an answer, but I'm very open for better options or other tools.
    – pLumo
    Commented Mar 24, 2022 at 9:51

2 Answers 2

1

I made a little script to do.

$ cat ~/bin/resize_picture:

#!/bin/bash

set -euo pipefail

usage(){
cat <<EOF
# USAGE:
    resize_picture TARGET_PX FILE...

# EXAMPLES:
    resize_picture 6000000 *.jpg
    find . -type f -name '*.jpg' resize_picture 8000000 {} +
EOF
exit
}

[ $# -lt 2 ] || [ "$1" = "-h" ] && usage

target=$1
shift

for file in "$@"; do
    printf "Processing %s ... " "$file"

    percent=$(
    identify -format '%w %h' -- "$file" \
    | awk -v t="$target" '
        $1*$2 > t  { r=$1/$2; printf "%.0f",sqrt(t*r)/$1*100 }
        $1*$2 <= t {printf "%d",100}
      '
    )

    if [ $percent -lt 100 ] ; then
        mogrify -resize "$percent"% "$file"
        printf 'Done (%d %%)\n' "$percent"
    else
        echo "Nothing to do"
    fi
done
0

convert accomplishes this task perfectly.

Ignore Aspect Ratio ('!' flag):

Ignore Aspect Ratio ('!' flag) If you want you can force "-resize" to ignore the aspect ratio and distort the image so it always generates an image exactly the size specified. This is done by adding the character '!' to the size. Unfortunately this character is also sometimes used for special purposes by various UNIX command line shells. So you may have to escape the character somehow to preserve it.

convert dragon_sm.gif -resize 64x64\! exact_dragon.gif convert terminal.gif -resize 64x64\! exact_terminal.gif

1
  • While this link may answer the question, it is better to include the essential parts of the answer here and provide the link for reference. Link-only answers can become invalid if the linked page changes. - From Review Commented Mar 14, 2023 at 16:56

You must log in to answer this question.

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