Wednesday, April 14, 2010

11:11 PM

Here is a simple function to calculate the width and height of an image given the constraints you want the image to fit in. This is great for creating thumbnails which need to fit into a specific height / width.

To call the function, pass in the current height / width of the image you’d like to resize along with the constrain dimensions of the final product. In this case, I’d like the thumbnail to fit within the constraints 125px X 125px. So, no matter what the dimensions returned will be within those confines.
If you don’t pass along a $constraintWidth or $constraintHeight [or pass them as 0], they will be set to the $width / $height.
Also, all parameters are assumed to be of the strict type int.
<?php
function getImageResizeDimensions($width,$height,$constraintWidth = 0,$constraintHeight = 0) {
$constraintWidth = ($constraintWidth === 0) ? $width : $constraintWidth;
$constraintHeight = ($constraintHeight === 0) ? $height : $constraintHeight;
if (($width > $constraintWidth) || ($height > $constraintHeight)) {
while (($constraintWidth < $width) || ($constraintHeight < $height)) {
if ($constraintWidth < $width) {
$height = floor((($constraintWidth * $height) / $width));
$width = $constraintWidth;
}
if ($constraintHeight < $height) {
$width = floor((($constraintHeight * $width) / $height));
$height = $constraintHeight;
}
}
retur
}
n array ($width,$height);
}
$imageURI = "/path/to/image.jpg";
list ($width,$height) = getimagesize($imageURI);
list ($newWidth,$newHeight) = getImageResizeDimensions($width,$height,125,125);
echo "newWidth: $newWidth\n";
echo "newHeight: $newHeight\n";
?>

0 comments: