Getting Proportionally-resized Dimensions of an Image

A PHP function that calculates the scaled-down dimensions of an image given a maximum width and height, while retaining the correct proportion.

get_resized_dimensions()

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

Parameters

ArgumentExplanation
$widthThe width of the image to be resized
$heightThe height of the image to be resized
$max_widthThe maximum allowed width of the resized image
$max_heightThe maximum allowed height of the resized image

Return Values

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

<?php
$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

<?php
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 );
   
}
?>

Comments

You can be the first person to comment on this article!

Add a comment

Name*

Email*

Never, ever sold or spammed :)

Homepage

Comment*

Sorry, plain text only :(