使用PHP调整扭曲的图像大小

时间:2013-01-04 21:36:11

标签: php image-processing image-resizing

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

我上传的任何照片似乎是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;
}
?>

1 个答案:

答案 0 :(得分: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);
}