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  

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

Unknown said...

kd 9 shoes
fitflops
ralph lauren pas cher
ugg boots
longchamp outlet
red bottoms
louboutin uk
rolex watches uk
adidas yeezy
coach factory outlet
20161228caiyan

Pfizer Center said...

Viagra Asli
Jual Viagra Asli
Obat Perangsang Pria
Kondom Sambung 18cm
Obat Perangsang Wanita
Obat Perangsang Pria
Kondom Sambung
Viagra Asli Usa
Opium Spray

yanmaneee said...

jordans
bape hoodie
kyrie shoes
supreme clothing
balenciaga shoes
yeezy shoes
kyrie 6
off white x jordan 1
yeezy supply
yeezy 500

Unknown said...

Great Article Image Processing Projects Deep Learning Projects for Final Year JavaScript Training in Chennai JavaScript Training in Chennai The Angular Training covers a wide range of topics including Components, Angular Directives, Angular Services, Pipes, security fundamentals, Routing, and Angular programmability. The new Angular TRaining will lay the foundation you need to specialise in Single Page Application developer. Angular Training Project Centers in Chennai

Unknown said...

안동출장샵
안동출장샵
전주출장샵
무주출장샵
전주출장샵
영주출장샵
군산출장샵

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


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


Unknown said...

세종출장안마
총판출장안마
총판출장안마
총판출장안마
고고출장안마
심심출장안마
제주출장안마
제주도출장안마

Post a Comment

Cron Design Studio: Dublin based web design & software development