使用PHP裁剪照片会变得很紧张

时间:2014-02-20 22:20:32

标签: php image image-processing thumbnails

我正在尝试调整大小并裁剪图片。

图片可以是横向或纵向,但我希望缩略图为250x250而不是拉伸(裁剪边或顶部/底部但保持大部分图像保持新尺寸,裁剪到正方形 - 有点像wordpress的缩略图)。

这是我的功能,它的大小合适,但它可以拉伸图片......

我做错了什么?

function make_thumb($src, $dest, $desired_width, $ext) {

    if ($ext == 'jpg' || $ext == 'jpeg') {
            $source_image = imagecreatefromjpeg($src);      
    }
    if ($ext == 'png') {
            $source_image = imagecreatefrompng($src);       
    }
    if ($ext == 'gif') {
            $source_image = imagecreatefromgif($src);       
    }   

    /* read the source image */
    $width = imagesx($source_image);
    $height = imagesy($source_image);

/* find the "desired height" of this thumbnail, relative to the desired width  */
    $desired_height = floor($height * ($desired_width / $width));
    $desired_height = 250;

    /* create a new, "virtual" image */
    $virtual_image = imagecreatetruecolor($desired_width, $desired_height);

    /* copy source image at a resized size */
    imagecopyresampled($virtual_image, $source_image, 0, 0, 0, 0, $desired_width, $desired_height, $width, $height);

    /* create the physical thumbnail image to its destination */

    if ($ext == 'jpg' || $ext == 'jpeg') {
            imagejpeg($virtual_image, $dest);       
    }
    if ($ext == 'png') {
            imagepng($virtual_image, $dest);        
    }
    if ($ext == 'gif') {
            imagegif($virtual_image, $dest);        
    }   
}

谢谢!

1 个答案:

答案 0 :(得分:1)

想一下你说的话。

如果更改图像的宽度并且不以与宽度完全相同的比例更改高度,则图像总是会变形。

你有正确的代码,没有失真,虽然我没有实际测试计算是正确的,然后你用任意高度250覆盖该计算。因此你得到一个失真。

注释掉这一行,它可能会停止失真

$desired_height = 250;

因此,如果您知道您总是想要一个250高度的图像,请更改计算以计算比例的新宽度,而不是将其作为参数传递。

function make_thumb($src, $dest, $desired_height = 250, $ext) {

    if ($ext == 'jpg' || $ext == 'jpeg') { $source_image = imagecreatefromjpeg($src);  }
    if ($ext == 'png') { $source_image = imagecreatefrompng($src); }
    if ($ext == 'gif') { $source_image = imagecreatefromgif($src); }   

    /* read the source image */
    $width = imagesx($source_image);
    $height = imagesy($source_image);

    /* calc the new width */
    $desired_width = floor($width * ($desired_height / $height));

    /* create a new, "virtual" image */
    $virtual_image = imagecreatetruecolor($desired_width, $desired_height);

    /* copy source image at a resized size */
    imagecopyresampled($virtual_image, $source_image, 0, 0, 0, 0, $desired_width, $desired_height, $width, $height);

    /* create the physical thumbnail image to its destination */

    if ($ext == 'jpg' || $ext == 'jpeg') { imagejpeg($virtual_image, $dest); }
    if ($ext == 'png') { imagepng($virtual_image, $dest); }
    if ($ext == 'gif') { imagegif($virtual_image, $dest); }   
}

当然,宽度会有所不同,具体取决于原始图像的实际尺寸。但是如果你想要停止失真,你必须让它发生。