# Simple Image Resize Calculator Function

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 = intval(floor(((\$constraintWidth * \$height) / \$width)));
\$width = \$constraintWidth;
}
if (\$constraintHeight < \$height) {
\$width = intval(floor(((\$constraintHeight * \$width) / \$height)));
\$height = \$constraintHeight;
}
}
}

# Some super short || skinny images will return 0 for these. Make sure that doesn't happen!
if (\$width < 1) {
\$width = 1;
}
if (\$height < 1) {
\$height = 1;
}

return 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";
?>

``````

Make a Comment

## One Response to “Simple Image Resize Calculator Function”

Como puedo hacer para que el php me rezise una imagen automaticamente sin deformarla? Where's The Comment Form?