在PHP中调整图像大小的智能方法

Psy*_*che 2 php image-manipulation

我想知道是否有人可以帮助我用PHP编写的图像大小调整功能但是必须调整图像的大小,但是像PHPThumb那样.因此,如果我设置新图像的宽度和高度,该函数必须适合新上传的图像(和宽高比)新的宽度和高度.

任何帮助表示赞赏.

谢谢.

Tra*_*isO 7

我几年前写过这篇文章,它确实是你正在寻找的.请记住,这只计算宽度和高度,您必须自己调用Imagick来实际应用这些计算.

/**
* ImageIntelligentResize()
* 
* @global Intelligently resizes images using a providid max width and height
* @param mixed $imagePath
* @param mixed $maxWidth
* @param mixed $maxHeight
* @param mixed $alwaysUpscale
* @return
*/
function ImageIntelligentResize( $imagePath, $maxWidth, $maxHeight, $alwaysUpscale )
{
    // garbage in, garbage out
    if ( IsNullOrEmpty($imagePath) || !is_file($imagePath) || IsNullOrEmpty($maxWidth) || IsNullOrEmpty($maxHeight) )
    {
        return array("width"=>"", "height"=>"");
    }

    // if our thumbnail size is too big, adjust it via HTML
    $size = getimagesize($imagePath);
    $origWidth = $size[0];
    $origHeight = $size[1];

    // Check if the image we're grabbing is larger than the max width or height or if we always want it resized
    if ( $alwaysUpscale || $origWidth > $maxWidth || $origHeight > $maxHeight )
    {   
        // it is so let's resize the image intelligently
        // check if our image is landscape or portrait
        if ( $origWidth > $origHeight )
        {
            // target image is landscape/wide (ex: 4x3)
            $newWidth = $maxWidth;
            $ratio = $maxWidth / $origWidth;
            $newHeight = floor($origHeight * $ratio);
            // make sure the image wasn't heigher than expected
            if ($newHeight > $maxHeight)
            {
                // it is so limit by the height
                $newHeight = $maxHeight;
                $ratio = $maxHeight / $origHeight;
                $newWidth = floor($origWidth * $ratio);
            }
        }
        else
        {
            // target image is portrait/tall (ex: 3x4)
            $newHeight = $maxHeight;
            $ratio = $maxHeight / $origHeight;
            $newWidth = floor($origWidth * $ratio);
            // make sure the image wasn't wider than expected
            if ($newWidth > $maxWidth)
            {
                // it is so limit by the width
                $newWidth = $maxWidth;
                $ratio = $maxWidth / $origWidth;
                $newHeight = floor($origHeight * $ratio);
            }
        }
    }
    // it's not, so just use the current height and width
    else
    {
        $newWidth = $origWidth;
        $newHeight = $origHeight;
    }   

    return array("width"=>$newWidth, "height"=>$newHeight);
}
Run Code Online (Sandbox Code Playgroud)