Resize rectangular image to square size with command-line utility convert

Resize rectangular image to square size using imagemagick’s command-line utility convert.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
function jpg_sqr() {
if [ "$#" -ne 2 ]; then
echo "Usage: jpg_sqr img.jpg size"
return 1
fi
fn=$(basename "$1")
ext="${fn##*.}"
fn="${fn%.*}"

convert "$1" -trim -set option:size '%[fx:max(w,h)]x%[fx:max(w,h)]' xc:white +swap \
-gravity center -resize $2"x"$2 -composite "$fn-square.jpg"
}

function png_sqr() {
if [ "$#" -ne 2 ]; then
echo "Usage: png_sqr img.png size"
return 1
fi
fn=$(basename "$1")
ext="${fn##*.}"
fn="${fn%.*}"

convert "$1" -trim -set option:size '%[fx:max(w,h)]x%[fx:max(w,h)]' xc:none +swap \
-transparent white \
-gravity center -resize $2"x"$2 -composite "$fn-square.png"
}

wiki.jpg

wiki1

> jpg_sqr wiki.jpg 400

wiki2

> png_sqr wiki.jpg 400

wiki3