Print Image With Fixed Aspect Ratio In PHP

20th September 2010

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.

  1. /**
  2.  * Calculates the aspect ratio of an image returns a formatted string
  3.  * containing the width and height of the image to a fixed width.
  4.  *
  5.  * @param string The name of the file
  6.  * @param integer The width of the image (optional)
  7.  *
  8.  * @return string The image dimentions.
  9.  */
  10. function img_aspect_ratio($file, $width = 200){
  11. if (!file_exists($file)){
  12. // File doesn't exist, return false.
  13. return '';
  14. }
  15.  
  16. // Get the image dimensions
  17. $image_size = getimagesize($file);
  18.  
  19. if ($image_size === false) {
  20. // Failed to get dimensions for image, return width
  21. return ' width="' . $width . '"';
  22. }
  23.  
  24. // Divide height by width to get the apect ratio.
  25. $aspect_ratio = $image_size[1] / $image_size[0];
  26.  
  27. // Change the height according to the aspect ratio
  28. $height = (int)($aspect_ratio * $width) . "px";
  29.  
  30. // Return formatted string of width and height
  31. return ' height="' . $height . '" width="' . $width . '"';
  32. }

You can use the function like this:

  1. $image_file = 'example_image.png';
  2.  
  3. echo '<img .="" img_aspect_ratio="" 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.