Search code examples
imagemagickimage-resizingimagemagick-convert

How to convert batch of rectangular images into square images without cropping?


Given batch of vertical and horizontal rectangular images :

enter image description here rect-h.png

enter image description here rect-v.png

How to convert batch of vertical and horizontal rectangular images into square images ?

So to get same sizes, not-cutted, no disformed :

enter image description here rect-h-sq.png

enter image description here rect-v-sq.png


I currently use

mkdir -p ./temp ./png                                  # create folders to work on copies of data and store final png output
cp ./* ./temp                                          # copies to ./temp, so to word on copies 
for file in ./temp/*.png                               # loop on the [edited] copies in ./temp
do
  keyIn=$(basename "$file" .png)                       # name of the file minus .png
  keyOut=$(basename "$file" .png)-sq.png               # name of the file minus .png, plus .-red.png 
  convert -background none -density 1200 ./temp/$keyIn.png -resize 300x300\! ./png/$keyOut   
done

But it fails.

Note: Density is there because I often work with svg as well.


Solution

  • Padding works :

    mkdir -p ./temp ./png                                  # create folders to work on copies of data and store final png output
    cp ./* ./temp                                          # copies to ./temp, so to word on copies 
    for file in ./temp/*.png                               # loop on the [edited] copies in ./temp
    do
      keyIn=$(basename "$file" .png)                       # name of the file minus .png
      keyOut=$(basename "$file" .png)-sq.png               # name of the file minus .png, plus .-red.png 
      convert -background none -density 1200 ./temp/$keyIn.png \
         -thumbnail '300x300>' -background white \
         -gravity center -extent 300x300 -resize 300x300\! ./png/$keyOut   
    done