PHP 图像调整为最小宽度/高度

tot*_*rds 2 php image-resizing

我一直试图弄清楚如何在 PHP 中调整上传图像的大小,使其不小于给定的大小 (650x650)。但是,如果用户上传的图像在任一边缘都小于我的 650 最小值,则无需采取任何措施。

场景 1 - 上传 2000 像素宽 x 371 像素的图像 - 这不会调整大小,因为 371 像素已经小于我的最小值。

场景 2 - 上传了 2000 像素 x 1823 像素的图像 - 在这里我应该将图像调整为尽可能接近最小值,但不允许宽度或高度低于 650 像素。

到目前为止,这是我一直在思考的路线(我正在使用优秀的 simpleImage 脚本来帮助调整大小和获取尺寸):

$curWidth = $image->getWidth();
$curHeight = $image->getHeight();               
$ratio = $curWidth/$curHeight;

if ($curWidth>$minImageWidth && $curHeight>$minImageHeight)
{
    //both dimensions are above the minimum, so we can try scaling
    if ($curWidth==$curHeight)
    {
        //perfect square :D just resize to what we want
        $image->resize($minImageWidth,$minImageHeight);
    }
    else if ($curWidth>$curHeight)
    {
        //height is shortest, scale that.
        //work out what height to scale to that will allow 
        //width to be at least minImageWidth i.e 650.   
        if ($ratio < 1) 
        {
            $image->resizeToHeight($minImageWidth*$ratio);
        } 
        else 
        {
            $image->resizeToHeight($minImageWidth/$ratio);
        }   
    }
    else
    {
        //width is shortest, so find minimum we can scale to while keeping
        //the height above or equal to the minimum height.
        if ($ratio < 1) 
        {
            $image->resizeToWidth($minImageHeight*$ratio);
        } 
        else 
        {
            $image->resizeToWidth($minImageHeight/$ratio);
        }   
}
Run Code Online (Sandbox Code Playgroud)

然而,这给了我一些奇怪的结果,有时它仍然会低于最小值。它唯一按预期工作的部分是尺寸高于最小值的测试 - 它不会缩放任何太小的东西。

我认为我最大的问题是我不完全理解图像纵横比和尺寸之间的关系,以及如何确定我能够缩放到的尺寸高于我的最小值。有什么建议?

Vyt*_*tas 5

尝试这个:

$curWidth = $image->getWidth();
$curHeight = $image->getHeight();               
$ratio = min($minImageWidth/$curWidth,$minImageHeight/$curHeight);
if ($ratio < 1) {
    $image->resize(floor($ratio*$curWidth),floor($ratio*$curHeight));
}
Run Code Online (Sandbox Code Playgroud)

或这个:

$image->maxarea($minImageWidth, $minImageHeight);
Run Code Online (Sandbox Code Playgroud)