1
votes

In my sites admin panel there is a option to upload images of different width and heights. I need to show those images in my home page with a fixed width of '176' and height of '100' .I set width and height as this in my home page:

<img src="<?php echo base_url()?>affliateimages/<?php echo $randimagep2->varaffimage ?>" width='176' height='100' />

But the problem is that when i upload a image of large/small width and height it shown as distorted in my home page. How can I resize image as propotion wise using php?

2

2 Answers

0
votes

I have made most of my scripts based on this simple class: here

Should do it.

0
votes
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 array(0=>$w,1=>$h,"width"=>$w,"height"=>$h);
 }else{//file does not exist or is not an image:
  return false;
 }
}

//usage $hwarr=resizeImg("imagepath",176,100);