'imagemagick resize to exact size

It's question more about "know-how". I have a bunch of images of completely different sizes: one could be 360x360 and another 1200x800. And I would to make thumbnails for a webpage of exact size, for example 150x150. Because of different sizes I can't just use convert -resize or just crop it some way, I need both. How would you solve this?



Solution 1:[1]

This question is quite old, but a current answer would be to use resize:

convert "input_filename" -resize '400x400!' "output_filename"

Note the exclamation point "!", which at least some shells require you to quote or escape to avoid history expansion.

Note that in requesting exact size, you may be asking for distortion.

Solution 2:[2]

You need a function that will calculate what the thumbnail sizes should be based on the source image width and height, and the max thumbnail width and height:

function setWidthHeight($srcWidth, $srcHeight, $maxWidth, $maxHeight){

    $ret = array($srcWidth, $srcHeight);

    $ratio = $srcWidth / $srcHeight;

    if($srcWidth > $maxWidth || $srcHeight > $maxHeight){

        $ret[0] = $maxWidth;
        $ret[1] = $ret[0] / $ratio;

        if($ret[1] > $maxHeight){
            $ret[1]  = $maxHeight;
            $ret[0] = $maxHeight * $ratio;
        }
    }    

    $ret[0] = intval(ceil($ret[0]));
    $ret[1] = intval(ceil($ret[1]));   

    return $ret;
}

You can then use whichever thumbnail image generating procedure you like imagecopyresampled(...) or the $imageMagick->thumbnailImage($newWidth, $newHeight);

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 jma
Solution 2 Danack