使用PHP调整图像大小,检测最长边并按比例缩放?

3
我正在使用PHP编写图片上传脚本,发现有人提供了一个脚本并尝试进行修改,但是遇到了一些问题。
我想要做以下事情: 检测图片的最长边(即竖向或横向), 然后重新调整图片大小,使最长边为800px且保持比例不变。
这是我目前的代码。对于横向的图片,它可以正常工作,但对于竖向的图片,会使它们失真。 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个回答

3
您可能误解了:
$width > $height时,表示它是横向的。将maxwidth设置为800意味着(height/width)*800 = 新高度。另一方面,$height > $width意味着将maxheight设置为800,因此(width/height)*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

希望你理解我的意思,你把它们搞反了 :) 还要注意的是,你在纵向缩略图中使用$newheight而不是$newheight1进行乘法运算。

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,则应将宽度设置为最大宽度,并根据其计算高度。如果比较的另一种方式只需将高度设置为最大高度并计算新宽度即可。


0

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

} else {


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


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

}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接