Here is a function to calculate the new dimensions of a thumbnail, to fit within the given dimensions on both sides.
<?php
/**
* Calculate new image dimensions to new constraints
*
* @param Original X size in pixels
* @param Original Y size in pixels
* @return New X maximum size in pixels
* @return New Y maximum size in pixels
*/
function scaleImage($x,$y,$cx,$cy) {
//Set the default NEW values to be the old, in case it doesn't even need scaling
list($nx,$ny)=array($x,$y);
//If image is generally smaller, don't even bother
if ($x>=$cx || $y>=$cx) {
//Work out ratios
if ($x>0) $rx=$cx/$x;
if ($y>0) $ry=$cy/$y;
//Use the lowest ratio, to ensure we don't go over the wanted image size
if ($rx>$ry) {
$r=$ry;
} else {
$r=$rx;
}
//Calculate the new size based on the chosen ratio
$nx=intval($x*$r);
$ny=intval($y*$r);
}
//Return the results
return array($nx,$ny);
}
?>
Use it like this:
<?php
//Read original image and create Imagick object
$thumb=new Imagick($originalImageFilename);
//Work out new dimensions
list($newX,$newY)=scaleImage(
$thumb->getImageWidth(),
$thumb->getImageHeight(),
$newMaximumWidth,
$newMaximumHeight);
//Scale the image
$thumb->thumbnailImage($newX,$newY);
//Write the new image to a file
$thumb->writeImage($thumbnailFilename);
?>
Imagick::thumbnailImage
(No version information available, might be only in CVS)
Imagick::thumbnailImage — 画像のサイズを変更する
説明
bool Imagick::thumbnailImage
( int $columns
, int $rows
[, bool $fit
] )
警告
この関数は、 現在のところ詳細な情報はありません。引数のリストのみが 記述されています。
画像のサイズを指定したものに変更し、関連付けられたプロパティをすべて削除します。 ウェブ上での表示に適した小さなサムネイル画像を作成します。 3 番目のパラメータに TRUE を指定すると、columns や rows にそれぞれの最大値を使用します。両方のパラメータが、 マッチするまであるいは指定したパラメータより小さくなるまで縮小されます。
パラメータ
- columns
-
画像の幅。
- rows
-
画像の高さ。
- fit
-
最大値を強制的に使用するかどうか。
返り値
成功した場合に TRUE を返します。
エラー / 例外
エラー時に ImagickException をスローします。
Imagick::thumbnailImage
Anonymous
02-Jul-2008 02:15
02-Jul-2008 02:15
n-sw-bit at ya dot ru
09-Jun-2008 07:48
09-Jun-2008 07:48
If you want to resize your picture to fit smallest parameter:
$fitbyWidth = (($maxWidth/$w)<($maxHeight/$h)) ?true:false;
if($fitbyWidth){
$im->thumbnailImage($maxWidth, 0, false);
}else{
$im->thumbnailImage(0, $maxHeight, false);
}
sgarner at expio dot co dot nz
17-Oct-2007 08:11
17-Oct-2007 08:11
With $fit == true, the image is resized proportionally so that its _smallest_ dimension matches the width or height specified, NOT both.
For example, if you say thumbnailImage(400, 400, true), on an image of 1600x800, it will be resized to 800x400, NOT 400x200 as you might expect.
The solution is to compare the original image's dimensions to the specified dimensions, and substitute zero for the smaller dimension, and set $fit = false.
i.e.: thumbnailImage(400, 0, false) would resize that 1600x800 image to 400x200.
raybdbomb . gmail
11-Sep-2007 02:18
11-Sep-2007 02:18
As noted here
http://php.net/manual/en/ref.imagick.php
With either of the params as 0, the aspect ratio is maintained.
