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

advertisements

I'm working on an image upload script with PHP, I found one someone was offering and tried modifying it, however, i'm running into a few problems.

I want to do the following: Detect the longest side of the image (ie. portrait or landscape) And then resize the image, with the longest side being 800px AND keep proportions.

Here is the code I have so far.. For landscape images it works fine, but with portrait ones it distorts them like crazy. PS. I'm making a larger image as well as a thumbnail.

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


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