Print Image With Fixed Aspect Ratio In PHP

When displaying images added by users it is quite often necessary to resize them in order that they fit into a specific area of the page. Not doing this can cause problems with the images breaking the page layout. The trouble is that if you resize the image absolutely you tend to squash and distort it.

The following function can be used to calculate the width and height of an image to the correct aspect ratio, which will preserve the contents when printed out. This function makes use of the getimagesize() function, which is available as part of the GD library in PHP.

/**
 * Calculates the aspect ratio of an image returns a formatted string
 * containing the width and height of the image to a fixed width.
 *
 * @param string  The name of the file
 * @param integer The width of the image (optional)
 *
 * @return string The image dimentions.
 */
function img_aspect_ratio($file, $width = 200){
    if (!file_exists($file)){
        // File doesn't exist, return false.
        return '';
    }

    // Get the image dimensions
    $image_size = getimagesize($file);

    if ($image_size === false) {
        // Failed to get dimensions for image, return width
        return ' width="' . $width . '"';
    }

    // Divide height by width to get the apect ratio.
    $aspect_ratio = $image_size[1] / $image_size[0];
     
    // Change the height according to the aspect ratio
    $height = (int)($aspect_ratio * $width) . "px";
     
    // Return formatted string of width and height
    return ' height="' . $height . '" width="' . $width . '"';    
}

You can use the function like this:

$image_file = 'example_image.png';

echo '<img' . img_aspect_ratio($image_file, 150) . ' src="' . $image_file . '" />';

I should note that this solution is far from perfect and shouldn't be used in all circumstances. It is best suited to resize images that only need a little tweak. For example, to resize the thumbnails in a gallery without having to regenerate all of the thumbnail images again.

This function shouldn't be used to resize large images down to small dimensions as your users will still need to download the full size images before they are resized in the browser. In this situation you should regenerate a smaller version of the image and then use this as the source of the image in the browser.

Add new comment

The content of this field is kept private and will not be shown publicly.
CAPTCHA
2 + 7 =
Solve this simple math problem and enter the result. E.g. for 1+3, enter 4.
This question is for testing whether or not you are a human visitor and to prevent automated spam submissions.