Getting Proportionally-resized Dimensions of an Image

A note from A Beautiful Site’s founder: We developed Surreal to be easy for you and your clients. If you’re a web designer, you should take a look at the simple, hosted CMS that’s changing the way content is managed. Surreal integrates in moments and is trusted by over 18,000 websites. Try it out for free and let us know what you think! Visit Website »

This is extremely useful when you need to scale down an image within a certain pair of dimensions.

get_resized_dimensions()

Parameters

Argument Explanation
$width The width of the image to be resized
$height The height of the image to be resized
$max_width The maximum allowed width of the resized image
$max_height The maximum allowed height of the resized image

Return Values

The function outputs an array containing two elements: width and height

$new_dimensions = get_resized_dimensions(640, 480, 200, 200)
echo $new_dimensions['width'] . ', ' . $new_dimensions['height'];

The output for the above code would be 200, 150.

Code

function get_resized_dimensions($width, $height, $max_width, $max_height) {

    // Check for bad values
    if( $width <= 0 || $height <= 0 ) return false;

    // Determine aspect ratio
    $aspect_ratio = $height / $width;

    // First check width
    if( $width > $max_width ) {
        $new_width = $max_width;
        $new_height = $new_width * $aspect_ratio;
    } else {
        $new_width = $width;
        $new_height = $height;
    }

    // Now check height
    if( $new_height > $max_height ) {
        $new_height = $max_height;
        $new_width = $new_height / $aspect_ratio;
    }

    return array( 'width' => $new_width, 'height' => $new_height );

}
If you enjoyed this article, please share it with a friend!

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>