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  

6 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.

Unknown said...


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


Post a Comment

Cron Design Studio: Dublin based web design & software development