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

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