21 April 2010

PHP: Image resize function for calculating & constraining image proportions to fit in a box or space

I wrote this function on the back of my Actionscript version to calculate the output size of an image. If you only have a certain amount of space available in your page layout and you need to dynamically display an image that you don't know the size of, then this function is for you.

You simply specify how much space you have and the function will calculate the new size of the image proportionately and (optionally) return the html img tag for the browser. Sounds simple but it's incredibly useful and a lot easier than coding this each time you have need.

Note: this does not resize the file on the server - it lets the browser do the resize. See comment below if you want to resize the original file.


The Function: (Please see right hand panel before copying) :

/*
PARAMS::::::::::::::::::::::
$imgsrc     //Movie clip to resize
$maxW      //maximum width
$maxH      //maximum height
$allowScaleUp   //defaults to 0 so as to not pixelate the image
$returnHTML    //attributes to attach to the returned img tag (set=0 to return values) 
USAGE:::::::::::::::::::::::
resizeImg("img.jpg",300,200)  //resizes proportionally to make the object fit in a 300X200px space
resizeImg("img.jpg",300,'*')  //resizes to 300 wide and calculates the height proportionally
resizeImg("img.jpg",'*',200)  //resizes to 200 high and calculates the width proportionally
resizeImg("img.jpg",300) //resizes protpotionally to make the largest side 300
resizeImg("img.jpg",null,200) //resizes proportionally to make the smallest side 200
RETURNS:::::::::::::::::::::::
if $returnHTML is 0 or false: returns an associative with keys: 'width' and 'height'
otherwise (if $returnHTML is a string): returns html img tag with specified attributes
False on error
*/
function resizeImg($imgsrc ,$maxW='*', $maxH='*', $allowScaleUp=0, $returnHTML="alt='image'"){
 if($s=getimagesize($imgsrc)){
  $oW=$s[0];$oH=$s[1];
  if(($oW>$maxW && $maxW!='*') || ($oH>$maxH && $maxH!='*') || $allowScaleUp){//if resize is needed:
   if($maxW && $maxH=='*'){ //constrain by width:
    $proportion=$oH/$oW;
    $w=$maxW;
    $h=$maxW*$proportion;   
   }else if($maxH && $maxW=='*'){ //constrain by height:
    $proportion=$oW/$oH;
    $h=$maxH;
    $w=$maxH*$proportion;
   }else if(!$maxW && $maxH){ //constrain by smallest side:
    return($oW>$oH ? resizeImg($imgsrc, '*', $maxH, $allowScaleUp, $returnHTML) : resizeImg($imgsrc, $maxW, '*', $allowScaleUp, $returnHTML));
   }else if($maxW && !$maxH){ //constrain by largest side:
    return($oW>$oH ? resizeImg($imgsrc, $maxW, '*', $allowScaleUp, $returnHTML) : resizeImg($imgsrc, '*', $maxH, $allowScaleUp, $returnHTML));
   }else{
    return($maxW>$maxH ? resizeImg($imgsrc, '*', $maxH, $allowScaleUp, $returnHTML) : resizeImg($imgsrc, $maxW, '*', $allowScaleUp, $returnHTML));
   }
  }else{
   $w=$oW;$h=$oH;
  }
  //echo "orig: ".$oW."x:".$oH."<br />max: ".$maxW."x".$maxH."<br />new: ".$w."x".$h."<br />"; //debug
  $w=round($w); $h=round($h);
  return ($returnHTML ? "<img src='$imgsrc' width='$w' height='$h' $returnHTML />" : array(0=>$w,1=>$h,"width"=>$w,"height"=>$h));
 }else{//file does not exist or is not an image:
  return false;
 }
}


//SAMPLE USAGE:
echo resizeImg("avatar.jpg",70,70,0,"alt='Daves Avatar' class='avatarImg'");
//prints img tag which resizes avatar.jpg proportionately to fit into 70*70 pixel space  

11 comments:

Unknown said...

If you want to resize the original image file rather than have the browser do it, just use this function in combination with PHP's image creation functions (imagejpeg, imagepng, etc). There are tutorials for this all over the web.

Anonymous said...

Great man!!! It is so simple to use.

Anonymous said...

Tried your code, but it does not constrain both sides when giving parameters for both, only one.

The last conditional of the 3rd nested if/then has:

return($maxW>$maxH ? resizeImg($imgsrc, '*', $maxH, $allowScaleUp, $returnHTML) : resizeImg($imgsrc, $maxW, '*', $allowScaleUp, $returnHTML));


Works if replaced with:

$proportion=$oW/$oH; $h=$maxH;
$w=$maxH*$proportion;

Vibha said...

Nice stuff..Thanks for sharing.

dagfaglie said...

The following system looks at exploiting patterns within the payment schedule over a longer time frame. Free Slots 1xbet korea Online No Download No Registration immediate play delivers all this without having you register for a service or obtain anything in any respect. + No cost, providing fun and playtime, no strings connected. Online scratch video games and free immediate video games are here too. Over 30 scratchies from Hacksaw Gaming and some from NextGen could have you revealing prizes instantly.

Anonymous said...


광양출장샵
광양출장샵
상주출장샵
진안출장샵
상주출장샵
전북출장샵
전북출장샵


Anonymous said...

I really appreciate the practical tips you offer in your posts. This one was particularly helpful. Thanks for sharing!

Anonymous said...

PHP: Image resize function for calculating & constraining image proportions to fit in a box or space Image Processing Projects For Final Year

de said...

The PHP function described here is a practical approach to handling images when a page has a fixed amount of available space. Instead of manually calculating dimensions each time, the function determines an appropriate output size while preserving the original image proportions. This makes it useful for applications where images come from different sources and may have unpredictable dimensions. Similar concepts can be explored through Image Processing Projects For Final Year, particularly projects involving image dimensions, presentation, and automated visual processing.

de said...

An important clarification in the article is that the function does not modify the original image file on the server; it allows the browser to display the image at the calculated dimensions. Separating display-size calculations from actual file processing is useful when designing image-based applications because presentation requirements and source-file manipulation are different concerns. Students exploring Image Processing Projects for IT can apply similar thinking when considering how image handling fits into larger software workflows.

de said...

The same resize-and-constrain concept can also be viewed as a simple example of an image-processing workflow: an input image is evaluated against available constraints, appropriate dimensions are calculated, and the result is presented without distorting its proportions. This kind of problem is a useful starting point for more advanced image-processing applications involving transformation, enhancement, or analysis. The topic can therefore provide inspiration for Image Processing Projects For Final Year, where practical visual problems can be developed into complete project implementations.

Post a Comment

Cron Design Studio: Dublin based web design & software development