比例明智的图像使用PHP调整大小

时间:2011-11-15 06:43:48

标签: php image resize

在我的网站管理面板中,您可以选择上传不同宽度和高度的图片。 我需要在我的主页上显示这些图像,其固定宽度为“176”,高度为“100”。我在我的主页中设置宽度和高度:

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

但问题是,当我上传大/小宽度和高度的图像时,它在我的主页中显示为扭曲。如何使用php将图像调整为propotion?

2 个答案:

答案 0 :(得分:0)

我根据这个简单的类创建了大部分脚本:here

应该这样做。

答案 1 :(得分:0)

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;
 }
}

//使用 $ hwarr = resizeImg( “的ImagePath”,176100);