Simple Image Resize Calculator Function

Posted on January 8, 2009. Filed under: GD, PHP |

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.

    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

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

One Response to “Simple Image Resize Calculator Function”

RSS Feed for Adventures in PHP / DHTML / CSS and MySQL Comments RSS Feed

Como puedo hacer para que el php me rezise una imagen automaticamente sin deformarla?

Where's The Comment Form?

Liked it here?
Why not try sites on the blogroll...

%d bloggers like this: