调整大小时的图像尺寸计算(php + imagemagick)

问题描述:

$size1 = 170;
$size2 = 128;


if($width > $height){

exec("convert ".$startfile." -resize x".$size2." -quality 100 ".$resultfile);

} else {

exec("convert ".$startfile." -resize ".$size1." -quality 100 ".$resultfile);
}

exec("convert ".$resultfile." -gravity Center -crop ".$size1."x".$size2."+0+0 ".$resultfile);

Need help to resize images 170x128 px. The function above works OK but there is one problem. As you can see, if image width is greater than height, the script first makes image 128 px height. The problem appears when there is a small difference between width and height.

For example, if image dimensions are 387x310 px, the script will use statement if($width > $height) and will make image 128px height. The problem is that at the same time image width will be resized to 160 px. But I need 170 pix width after resizing.

I need to know what will be image width after resizing it to 128 px height. I need something like this:

if($width > $height && $width_after_resizing > 127) {
} else {
}

Is there any way how to calculate image dimensions before cropping it? Thanks.

Checking $width against $height assumes the target will be square. What if you change:

if($width > $height){

to

if($width/$size1 > $height/$size2){

if you have gd enabled you can use getimagesize http://php.net/manual/en/function.getimagesize.php

You want to turn of aspect ratio to get exactly the size specified.

Add a '!' to the -resize argument.

For more direct information about imagemagick fo to the IM forums http://www.imagemagick.org/discourse-server/viewforum.php?f=1