2

我有一个上传表单,您可以在其中选择照片。上传后,如有必要,我会调整图像大小。

似乎我上传的任何照片都HEIGHT > WIDTH拉伸了图像。如果我上传一张WIDTH > HEIGHT可以正常工作的图片。我一直在绞尽脑汁想弄清楚这一点。我很确定我知道哪一行是问题所在,并且我已经在评论中指出了这一点。

谁能看出我的数学有什么问题?谢谢!

<?php
$maxWidth  = 900;
$maxHeight = 675;
$count     = 0;

foreach ($_FILES['photos']['name'] as $filename)
{
    $uniqueId   = uniqid();
    $target     = "../resources/images/projects/" . strtolower($uniqueId . "_" . $filename);
    $file       = $_FILES['photos']['tmp_name'][$count];    
    list($originalWidth, $originalHeight) = getimagesize($file);

    // if the image is larger than maxWidth or maxHeight
    if ($originalWidth > $maxWidth || $originalHeight > $maxHeight)
    {
        $ratio = $originalWidth / $originalHeight;

        // I think this is the problem line
        (($maxWidth / $maxHeight) > $ratio) ? $maxWidth = $maxWidth * $ratio : $maxHeight = $maxWidth / $ratio; 

        // resample and save
        $image_p    = imagecreatetruecolor($maxWidth, $maxHeight);
        $image      = imagecreatefromjpeg($file);
        imagecopyresampled($image_p, $image, 0, 0, 0, 0, $maxWidth, $maxHeight, $originalWidth, $originalHeight);
        $image      = imagejpeg($image_p, $target, 75);
    }
    else
    {
        // just save the image
        move_uploaded_file($file,$target);
    }
    $count += 1;
}
?>
4

1 回答 1

3

缩放时,需要同时修改目标的宽度和高度。

尝试:

if ($originalWidth > $maxWidth || $originalHeight > $maxHeight)
{
    if ($originalWidth / $maxWidth > $originalHeight / $maxHeight) {
        // width is the limiting factor
        $width = $maxWidth;
        $height = floor($width * $originalHeight / $originalWidth);
    } else { // height is the limiting factor
        $height = $maxHeight;
        $width = floor($height * $originalWidth / $originalHeight);
    }
    $image_p    = imagecreatetruecolor($width, $height);
    $image      = imagecreatefromjpeg($file);
    imagecopyresampled($image_p, $image, 0, 0, 0, 0, $width, $height, $originalWidth, $originalHeight);
    $image      = imagejpeg($image_p, $target, 75);
}
于 2013-01-04T21:44:38.780 回答