Resize image with PHP, detect longest side, and resize according?

十年热恋 提交于 2019-12-06 00:37:29

You're probably mistaking:

When $width > $height that means it's landscape. Setting maxwidth to 800 means (height/width)*800 = new height. On the other hand $height > $width means setting maxheight to 800 and thus having (width/height)*800 is new width.

Right now your using both the height/width ratio instead of the other way around. Example:

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

Hope you get what I'm saying, you just switched them :) Also notice that you multiply with $newheight instead of $newheight1 for the portrait thumbnail

You can take a look in this function I use in my Image class:

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

Basically it first calculates the image's proportions in $rate based on width/height. Then it checks if the width is going to get out of bounds when resized ( $this->width / $MaxWidth > $this->height / $MaxHeight ) and if it is - sets width to the desired maximum width and calculates the height accordingly.

$this->width / $MaxWidth is the percentage of the image's width based on the maximum one. So if $this->width / $MaxWidth is larger than $this->height / $MaxHeight the width should be set to maxwidth and the height should be calculated based on it. If the comparison is the other way around just set height to maxheight and calculate the new width.

You should switch height and width in the second part, note the ($width/$height) part:

} else {


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


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

}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!