PHP – Recalculation of image sizes by limit for max. width or height keeping aspect ratio
(returns sizes and HTML attributes)
probably 2013
Simple PHP function, whose purpose is to change image size.
If you have image with absolutely any (unknown) aspect ratio (which you can't change),
and you also have limits for maximal height and maximal width of image, to it fit into your website layout,
this function is waiting for you.
/******Recalculation of size of image by limit for width or height, keeping aspect ratio********/ function new_image_size($width, $height, $maxwidth, $maxheight=0) { // Input parameters: // 2x actual size of image (But you can use native function getimagesize() instead of them, in the most of cases); // 2x maximal requested size of image (0 == unlimited), you can ignore last parameter for maxheight (it will be 0 == unlimited) // You can give imagesizes with any real aspect ratio on the input (it can be another aspect ratio than aspect ratio of limit size). // You can give limit for width, for height, or for both ones on the input // You will get width, height and XHTML code for size containing both of that numbers on the output // Author: Martin Adámek, www.adamek.cz, Náchod, Czech Republic // Lot of similar functions exist on the internet, but searching of some universal the same way like this would waste more time than to type this one: if (($maxheight>0)and($maxheight<$height)) { $width = $width*$maxheight/$height; $height = $maxheight; } //Do not use 'elseif' (n)or 'else' here! Function is ready for sizes of image with aspect ratio very different from aspect ratio of limits for size. So it is possible that size will be corrected already in first step, but it will not be enough, so it will be corrected again in second step! if (($maxwidth>0)and($maxwidth<$width)) { $height = $height*$maxwidth/$width; $width = $maxwidth; } return array($width, $height, 'width="'.$width.'" height="'.$height.'"'); }