【问题标题】:Cropping images in PHP leaves black space在 PHP 中裁剪图像会留下黑色空间
【发布时间】:2017-10-27 16:00:54
【问题描述】:

这可能是重复的,但我看过的每个解决方案似乎都不适合我,所以不确定我在做什么不同。

我对图像处理还不太了解,但是当使用 imagecopyresampled 将图像放置在另一个图像上时,裁剪图像似乎会在图像的右侧/底部添加大量黑色空间。它们都是 JPEG。

这是我的裁剪功能:

function thumbImage($thumb_img,$img_size,$shape){
    $width = 250;
    $height = 250;

    list($w, $h) = $img_size;

    if($w > $h) {
            $new_height =   $height;
            $new_width  =   floor($w * ($new_height / $h));
            $crop_x     =   ceil(($w - $h) / 2);
            $crop_y     =   0;
    } else {
            $new_width  =   $width;
            $new_height =   floor( $h * ( $new_width / $w ));
            $crop_x     =   0;
            $crop_y     =   ceil(($h - $w) / 2);
    }

    $tmp_img = imagecreatetruecolor($width,$height);
    imagecopyresampled($tmp_img, $thumb_img, 0, 0, $crop_x, $crop_y, $new_width, $new_height, $w, $h);

    return $tmp_img;
}

任何解释其工作原理的解决方案将不胜感激。

【问题讨论】:

    标签: php gd crop


    【解决方案1】:

    试试这个:

    function thumbImage($source_img,$max_size){
    
        list($w, $h) = getimagesize($source_img);
    
        if($w>$h){
            $width = ($max_size/$h)*$w;
            $height = $max_size;
        }else{
            $width = $max_size;
            $height = ($max_size/$w)*$h;
        }
    
        $x = ($max_size-$width)/2;
        $y = ($max_size-$height)/2;
    
        $thumb_img = imagecreatetruecolor($max_size,$max_size);
        imagecopyresampled($thumb_img, $source_img, $x, $y, 0, 0, $width, $height, $w, $h);
    
        return $thumb_img;
    }
    

    【讨论】:

    • 谢谢,但结果完全一样,如果问题可能存在,我可以在添加图像的位置添加代码?
    • 是的,请发布。我发布的代码应该可以工作,我自己使用它没有问题。