2011-05-06 90 views
3

我正在使用PHP的图片上传脚本,我发现有人提供并尝试修改它,但是,我遇到了一些问题。使用PHP调整图像大小,检测最长边,并根据大小调整大小?

我要做到以下几点: 检测的图像(即纵向或横向)。 的最长的一边,然后调整图像大小,最长边为800像素,并保持比例。

这是我到目前为止的代码。对于风景图像,它可以很好地工作,但是对于肖像,它会像疯了一样扭曲它们。 PS。我正在制作更大的图片以及缩略图。

list($width,$height)=getimagesize($uploadedfile); 

if($width > $height){ 

    $newwidth=800; 
    $newheight=($height/$width)*$newwidth; 

    $newwidth1=150; 
    $newheight1=($height/$width)*$newwidth1; 

} else { 


    $newheight=800; 
    $newwidth=($height/$width)*$newheight; 


    $newheight1=150; 
    $newwidth1=($height/$width)*$newheight; 

} 
$tmp=imagecreatetruecolor($newwidth,$newheight); 
$tmp1=imagecreatetruecolor($newwidth1,$newheight1); 

回答

3

你可能会误以为:

$width > $height这意味着它的景观。将最大宽度设置为800意味着(高度/宽度)* 800 =新的高度。另一方面,$height > $width意味着将maxheight设置为800,因此具有(宽度/高度)* 800是新的宽度。

现在你使用高/宽比而不是其他方式。例如:

Image: 1600 (w) x 1200 (h) 
Type: Landscape 
New Width: 800 
New Height: (1200 (h)/1600(w) * 800 (nw) = 600 

Image 1200 (w) x 1600 (h) 
Type: Portrait 
New Height: 800 
New Width: (1200 (w)/1600(h) * 800 (nh) = 600 

希望你得到我在说什么,你只是交换他们:)还要注意,你有$ newheight1 newheight而不是$繁殖的肖像缩略图

0

您可以一看这个函数我在我的Image类中使用:

public function ResizeProportional($MaxWidth, $MaxHeight) 
{ 

    $rate = $this->width/$this->height; 

    if ($this->width/$MaxWidth > $this->height/$MaxHeight) 
     return $this->Resize($MaxWidth, $MaxWidth/$rate); 
    else 
     return $this->Resize($MaxHeight * $rate, $MaxHeight); 
} 

基本上它首先根据宽度/高度计算图像在$ rate中的比例。然后它会检查宽度是否会在调整大小($this->width/$MaxWidth > $this->height/$MaxHeight)时超出范围,如果是 - 将宽度设置为所需的最大宽度并相应地计算高度。

$this->width/$MaxWidth是基于最大值的图像宽度的百分比。因此,如果$this->width/$MaxWidth大于$this->height/$MaxHeight,则应将宽度设置为最大宽度,并应根据此高度计算高度。如果比较是刚刚将高度设置为maxheight并计算新宽度的其他方法。

0

你应该切换的高度和宽度在第二部分中,注意($width/$height)部分:

} else { 


    $newheight=800; 
    $newwidth=($width/$height)*$newheight; 


    $newheight1=150; 
    $newwidth1=($width/$height)*$newheight; 

}