【问题标题】:How do I Resize images to fixed width & height while maintaing aspect ratio in PHP?如何在 PHP 中保持纵横比的同时将图像大小调整为固定宽度和高度?
【发布时间】:2019-01-08 06:53:57
【问题描述】:

我正在尝试在 PHP 中批量调整图像大小为 250 x 250

所有源图像都大于 250 x 250,这很有帮助。

我想保持纵横比,但将它们全部设为 250 x 250。我知道会裁剪掉一部分图像来执行此操作。这对我来说不是问题

问题是我当前的脚本仅适用于宽度并根据纵横比制作高度,但有时,图像现在最终会变成 250 x 166。我不能使用它。

因此需要以相反的方式调整大小(从高度到宽度)

脚本必须如何才能始终使最终图像为 250 x 250 而无需拉伸。同样,我不在乎是否有种植。我想在某个地方会有一个 else ,但现在这已经超出了我的想象。我更像是一个前端的人。

任何帮助都会很棒。

以下只是我完整脚本的相关部分:

$width = 250;
$height = true;

 // download and create gd image
 $image = ImageCreateFromString(file_get_contents($url));

 // calculate resized ratio
 // Note: if $height is set to TRUE then we automatically calculate the height based on the ratio
 $height = $height === true ? (ImageSY($image) * $width / ImageSX($image)) : $height;

 // create image 
 $output = ImageCreateTrueColor($width, $height);

 ImageCopyResampled($output, $image, 0, 0, 0, 0, $width, $height, ImageSX($image), ImageSY($image));

 // save image
 ImageJPEG($output, $destdir, 100); 

【问题讨论】:

    标签: php resize crop aspect-ratio


    【解决方案1】:
        $newWidth = 250;
        $newHeight = 250;
    
        // download and create gd image
        $image = ImageCreateFromString(file_get_contents($url));
        $width = ImageSX($image);
        $height = ImageSY($image);
    
        $coefficient =  $newHeight / $height;
        if ($newHeight / $width > $coefficient) {
            $coefficient = $newHeight / $width;
        }
    
        // create image
        $output = ImageCreateTrueColor($newWidth, $newHeight);
    
        ImageCopyResampled($output, $image, 0, 0, 0, 0, $width * $coefficient, $height * $coefficient, $width, $height);
    
       // save image
       ImageJPEG($output, $destdir, 100); 
    

    【讨论】:

    • 太棒了!非常感谢。我很感激。效果很好!
    • 宽度系数使用高度参数进行计算 - 应该更改它以避免生成不适合所需高度/宽度的图像。 如果 (($target_width / $width) > $coefficient) { $coefficient = $target_width / $width; }
    猜你喜欢
    • 2012-01-03
    • 2015-05-22
    • 2019-10-11
    • 2021-02-09
    • 2013-04-03
    • 2015-10-26
    • 2020-10-20
    • 2013-07-07
    • 2017-02-13
    相关资源
    最近更新 更多