【问题标题】:Distorted image resize with PHP使用 PHP 调整扭曲的图像大小
【发布时间】:2013-01-04 21:36:10
【问题描述】:

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

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

【问题讨论】:

    标签: php image-processing image-resizing


    【解决方案1】:

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

    试试:

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

    【讨论】:

    • 我怎么不认为两者都需要改变,这超出了我的想象,哈哈……那行得通!非常感谢!我会在 1 分钟内接受你的回答
    猜你喜欢
    • 2016-04-02
    • 1970-01-01
    • 2012-10-16
    • 2020-09-29
    • 1970-01-01
    • 2015-04-18
    • 2016-09-11
    • 2019-11-11
    • 2012-02-28
    相关资源
    最近更新 更多