【问题标题】:PHP - Create thumbnail from picture and keeping proportionPHP - 从图片创建缩略图并保持比例
【发布时间】:2023-01-13 05:03:36
【问题描述】:

我想创建一个没有黑/白条的缩略图并让它保持纵横比

缩略图大小应为 320x200 (px)。

我实际上写了一个函数来为给定的分辨率创建缩略图,但我不知道如何保持图像的纵横比

function imageResize($imageResourceId, $width, $height)
{
    $targetWidth = 320;
    $targetHeight = 200;

    
    $targetLayer = imagecreatetruecolor($targetWidth, $targetHeight);

    imagecopyresampled($targetLayer, $imageResourceId, 0, 0, 0, 0, $targetWidth, $targetHeight, $width, $height);

    return $targetLayer;

}

但是我想不出一种方法来裁剪它们并根据需要容纳它们。提前致谢!

【问题讨论】:

    标签: php image gd


    【解决方案1】:

    为此,您可以像这样使用 imagecopyresampled 函数:

    function imageResize($imageResourceId, $width, $height)
    {
        $targetWidth = 320;
        $targetHeight = 200;
    
        $aspectRatio = $width / $height;
        $targetRatio = $targetWidth / $targetHeight;
    
        if ($aspectRatio > $targetRatio) {
            $newHeight = $targetHeight;
            $newWidth = $targetHeight * $aspectRatio;
        } else {
            $newWidth = $targetWidth;
            $newHeight = $targetWidth / $aspectRatio;
        }
        $targetLayer = imagecreatetruecolor($newWidth, $newHeight);
        imagecopyresampled($targetLayer, $imageResourceId, 0, 0, 0, 0, $newWidth, $newHeight, $width, $height);
        return $targetLayer;
    }
    

    使用这个,新的宽度和高度是根据原始图像的纵横比计算的。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-06-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-05-04
      • 2023-04-09
      • 2015-05-06
      • 1970-01-01
      相关资源
      最近更新 更多