php - 使用 PHP 调整扭曲图像大小

标签 php image-processing image-resizing

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

似乎我上传的任何照片都在 HEIGHT > WIDTH 处拉伸(stretch)了图像。如果我上传 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;
}
?>

最佳答案

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

尝试:

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

关于php - 使用 PHP 调整扭曲图像大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14165386/

相关文章:

php - 来自两个不同行的 mysql_fetch_array

javascript - AngularJS、DropzoneJS、JSON -- 上传成功后刷新文件列表

html - 如何在CSS中设置图像的最大宽度

node.js - Jimp 从 url 读取、调整大小和显示图像

php - PDO 查询在结果集中返回每个字段两次

php - yii2 Controller Action 注入(inject)是如何工作的

java - 如何找到图像的主色?

c++ - 使用 Mat::at<Vec3i> 点未分配正确的像素

python - 使用opencv,tensorflow和python进行人体检测

php - 在 PHP 中调整图像大小而不使用第三方库?