Search code examples
resizecropedge-detectiongraphicsmagickpicturefill

How do I crop/resize a background/border out of an image with GraphicsMagick


I have some images in a large set of images that have a white (or black) border that surrounds the image itself. How can I...

  1. Crop the image to a size without said background/border
  2. Resize the image to fill a given output size centered.

For example, I have an uploaded image that is 1280x1024px in size, this has a white (or black) border where the interior size is say 800x700 (may not be centered), I want to crop out that border, then resize to fill a 640x480 output. This will effectively take the interior image, then fill the 640x480 effectively cropping an additional 100px of height from the original.


I'd prefer something that can be a batch/shell script with graphics magick, but will accept a solution via phantomjs as well. I'd prefer to avoid additional tools/languages if at all possible.


Solution

  • Trim will remove borders according corners pixels,

    Extent and Gravity will make the image a certain size and align it accordingly,

    Also see Geometry parameters,

    convert -trim source.png trim.png
    convert -extent 800x600 -gravity center trim.png frame.png
    

    enter image description here

    Here are the dimensions of the images shown :

    • Source : 722 x 480
    • Trim : 640 x 400
    • Frame : 800x 600

    EDIT

    This will resize the image to fit 800 pixels wide, and make its height 600 if it is less:

    enter image description here

    convert -resize 800x600^ -extent 800x600 -gravity center trim.png resize.png
    

    See http://www.imagemagick.org/Usage/resize/#fill for all the details, particulary you should test how it behaves on portrait images.

    Also, if you remove 800 at the resize parameter, it will fit by its height :

    enter image description here

    convert -resize x600^ -extent 800x600 -gravity center trim.png resize.png
    

    EDIT 2

    You must use the caret with one of the axes :

    convert -resize 1200^ -extent 1200x600 -gravity center trim.png resize1.png
    

    enter image description here

    As you can see, top and bottom have been trimmed and the image is fitted according its width.