Search code examples
bashimageshellimagemagickcrop

imagemagick: crop one image to four not equal size parts, but but keep original canvas size and paint background transparent


I have a 1920X1920 ratio image like below: origial image

I want to crop this original image so that it is divided into four parts. enter image description here In the end it has the effect of forming four pictures, each of which is the original size. enter image description here

I have used such a command, but this intelligence forms two pictures up and down, and cannot form four transparent pictures

convert lena.png -crop 1x2@ +adjoin lena_%02d.miff
for img in *.miff; do
name=$(convert $img -format %t info:)
convert $img -background transparent -flatten $name.png
done
rm -f *.miff

Excuse me, is there a very elegant way to achieve the effect I dream of?


Solution

  • Note: Since the image you're probably working with is not the image you posted, you will need to modify this code to suit your purposes.

    #!/bin/bash
    
    width=$(convert lena.png -format "%w" info:)
    height=$(convert lena.png -format "%h" info:)
    
    # Get the Percentage of the Width
    pct_w() {
      echo $(($1*$width/100))
    }
    
    # Get the Percentage of the Height
    pct_h() {
      echo $(($1*$height/100))
    }
    
    # Top-Left
    convert lena.png -crop $(pct_w 33)x$(pct_h 50)+0+0 +adjoin top-left.miff
    convert top-left.miff -background transparent -flatten top-left.png
    
    # Top-Right
    convert lena.png -crop $(pct_w 66)x$(pct_h 50)+$(pct_w 33)+0 +adjoin top-right.miff
    convert top-right.miff -background transparent -flatten top-right.png
    
    # Bottom-Left
    convert lena.png -crop $(pct_w 65)x$(pct_h 50)+0+$(pct_h 50) +adjoin bottom-left.miff
    convert bottom-left.miff -background transparent -flatten bottom-left.png
    
    # Bottom-Right
    convert lena.png -crop $(pct_w 35)x$(pct_h 50)+$(pct_w 65)+$(pct_h 50) +adjoin bottom-right.miff
    convert bottom-right.miff -background transparent -flatten bottom-right.png
    
    rm *.miff
    

    There are two helper functions to calculate percentages for Width and Height. In the code $(pct_w 33) this refers to 33% of the width. Change these values accordingly until you get the cuts you want.