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
(PECL imagick 2.0.0)
Imagick::thumbnailImage — Cambia el tamaño de una imagen
Descripción
Esta función no está documentada actualmente, solamente se encuentra disponible la lista de parámetros.
Cambia el tamaño de una imagen a las dimensiones dadas y elimina cualquier perfil asociado. El objetivo es producir conjuntos de imágenes de miniaturas pequeñas de bajo coste para mostrar en la web. Si TRUE se da como tercer parámetro, los parámetros columns (columnas) y rows (filas) se usan como máximos para cada cara. Ambas caras serán escaladas a una proporción menor hasta que la comparación sea menor que el parámetro dado para la cara.
Note: La conducta del parámetro bestfit cambió en Imagick 3.0.0. Antes de esta versión dar la dimensión de 400x400 a una imagen de 200x150 debería no tener efecto. En Imagick 3.0.0 y superiores la imagen sería llevada al tamaño de 400x300 ya que este es el "mejor ajuste" para las dimensiones dadas. Si el parámetro bestfit es utilizado, se debe indicar tanto el ancho como el alto.
Parámetros
- columns
-
Ancho de la imagen
- rows
-
Alto de la imagen
- bestfit
-
Si se fuerzan valores máximos
Valores devueltos
Devuelve TRUE en caso de éxito.
Errores/Excepciones
Lanza ImagickException en caso de error.
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);
}
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.
As noted here
http://php.net/manual/en/ref.imagick.php
With either of the params as 0, the aspect ratio is maintained.
