Search code examples
imageimage-processingimagemagickgraphicsmagick

Resize without whitespace surrounding on images using graphicsmagick or imagemagick


I'm using graphicsmagick to resize an image to a thumbnail, but it's adding a white surrounding border padding.

enter image description here

The command I'm using is:

gm convert matrix.jpg -resize "80x80>" -gravity center -extent 80x80 thumbnail.jpeg

As you can see, there is some white padding around the image, but I don't want this. Ideally I'd like (the entire image not just a crop of it) to fill the desired 80x80 output size.

How can this be achieved in either imagemagick or graphicsmagick?


Solution

  • I used ImageMagick with this image. This solution requires to know the size of the input image.

    Input

    Input

    The image has 145 pixels horizontally and 200 pixels vertically.

    Crop

    Crop from the top of the image:

    convert -crop 145x145+0+0 -resize 80x80 matrix.jpg thumbnail.jpeg
    

    I used 145x145 in order to extract a square from the original image. +0+0 is the offset of the extracted square, hereby the top left.

    Crop

    Crop with the center of the image:

    convert -crop 145x145+0+27 -resize 80x80 matrix.jpg thumbnail.jpeg
    

    Crop

    The vertical offset is set to 27 because we have to remove 55 (200 - 145) pixels on top or bottom, so we need to remove 27 (55 ÷ 2) pixels on the top and 28 pixels on the bottom.

    Crop with the bottom of the image:

    convert -crop 145x145+0+55 -resize 80x80 matrix.jpg thumbnail.jpeg
    

    Crop

    Resizing without crop

    convert -resize 80x80\! matrix.jpg thumbnail.jpeg
    

    The ! flag (escaped with \! as suggested in the documentation) after the resize parameters forces ImageMagick to ignore the aspect ratio.

    Ignore aspect ratio