繁体   English   中英

php imagecopyresampled无法按预期工作

[英]php imagecopyresampled not working as expected

我试图在将图像保存到ftp服务器之前使用imagecopyresampled裁剪图像。

我的PHP是:

function image_resizing($image, $type, $ext, $quality, $file_name) {
    strtolower($ext);
    list($src_width, $src_height) = getimagesize($image);
    switch($ext) {
        case 'gif':
        $image_create = 'imagecreatefromgif';
        break;

        case 'png':
        $image_create = 'imagecreatefrompng';
        break;

        default:
        $image_create = 'imagecreatefromjpeg';
        break;        
    } 

    $temp_img = $image_create($image);

    if($type == 'wide') {
        $width = 1920;
        $height = 2160;
    } else if($type == 'content') {
        $height = 600;
        $width = 400;
    }

    $src_x = ($src_width - $width) / 2;
    $src_y = ($src_height - $height) / 2;

    $new_image = imagecreatetruecolor($width, $height);
    imagecopyresampled ($new_image, $temp_img, 0, 0, $src_x, $src_y, $width, $height, $src_width, $src_height);
    $image_dest = '';
    imagejpeg($new_image, $file_name, $quality);
}

但是不知何故,我最终在裁切区域周围留有黑色空间,或者在新图像中全都是黑色(在较小的图像中)。 据我所知src / dest坐标是正确的。

图片:

http://www.strongleaf.nl/images/website_images/content-images/image-test-image-imagecopyresampled.jpg

http://www.strongleaf.nl/images/website_images/wide-images/image-test-image-imagecopyresampled.jpg

如果原始图像较大,则我认为pb是imagecopyresampled的最后两个参数在原始图像外定了一个矩形。 你能试一下吗 :

imagecopyresampled ($new_image, $temp_img, 0, 0, $src_x, $src_y, $width, $height, $width, $height);

我看到一些问题:

1)您应该将imagecopyresampled更改为(注意最后两个参数)

imagecopyresampled ($new_image, $temp_img, 0, 0, $src_x, $src_y, $width, $height, $width, $height);

2)你应该有

$ext = strtolower($ext);

3)$ width,$ height将为零,以防您将错误的$ type传递给函数


但是,即使缩放比例小于1920x2160或400x600,也仍然要避免图像周围的黑色空间。

我建议不要理会GD 改用Imagick

您可以在Imagick中调用:: cropthumbnailimage ,它将解决尺寸方面的所有问题。 我开始使用Imagick的主要原因是GD库的内存使用率很高。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM