繁体   English   中英

PHP调整大小并裁剪居中的顶部图像

[英]PHP resize and crop centered-top image

我正在尝试调整大小(保持宽高比)并裁切多余的图像(超出缩略图限制),但是在裁切x =中心和y =顶部的同时这样做。

我在这里丢失了一些东西,但是我的最终图像适合缩略图区域,而不是填充并裁剪多余的图像。 希望有人可以帮助我。

到目前为止,这是我的代码:

$image_width = 725; // not static, just an example
$image_height = 409; // not static, just an example

// image can be wide or portrait

$width = 140;
$height = 160;

$thumbnail = imagecreatetruecolor($width, $height); 
$white = imagecolorallocate($thumbnail, 255, 255, 255);
imagefill($thumbnail, 0, 0, $white);        

$width_ratio = $image_width/$width;
$height_ratio = $image_height/$height;

if ($width_ratio>$height_ratio) {
    $dest_width=$width;
    $dest_height=$image_height/$width_ratio;        
}
else{       
    $dest_width=$image_width/$height_ratio;
    $dest_height=$height;           
}   

$int_width = ($width - $dest_width)/2;
$int_height = ($height - $dest_height)/2;        

imagecopyresampled($thumbnail, $original_image, $int_width, $int_height, 0, 0, $dest_width, $dest_height, $image_width, $image_height);  

谢谢!

您的$image_width$image_height$width$height是静态的,这意味着$width_ratio$height_ratio总是相同的(分别为: 5.17857142857142.55625 ,因此宽度比始终2.55625高度比)。

在这种情况下,您的代码块如下:

if ($width_ratio>$height_ratio) {
    $dest_width=$width;
    $dest_height=$image_height/$width_ratio;        
}
else{       
    $dest_width=$image_width/$height_ratio;
    $dest_height=$height;           
}

将始终运行if再也不else -删除它,只留下:

$dest_width=$image_width/$height_ratio;
$dest_height=$height; 

并根据较高的值裁剪图像-在这种情况下,高度将根据新的高度调整大小,多余的宽度将被切除。

希望这就是您想要的!

编辑:

现在,如果相等地切除边缘,则执行脚本。 如果要从顶部或左侧完全切割它们(取决于比例),则:

完全删除该部分代码:

$int_width = ($width - $dest_width)/2;
$int_height = ($height - $dest_height)/2;

更改if else之前提到的条件:

if($width_ratio < $height_ratio) {
    $dest_width=$width;
    $dest_height=$image_height/$width_ratio;

    $int_width = ($width - $dest_width)/2;
    $int_height = 0;
} else {       
    $dest_width=$image_width/$height_ratio;
    $dest_height=$height;

    $int_width = 0;
    $int_height = ($height - $dest_height)/2;
}

编辑2

水平总是切成相等,垂直总是从顶部切成-如您所愿:

if($width_ratio < $height_ratio) {
    $dest_width=$width;
    $dest_height=$image_height/$width_ratio;
} else {       
    $dest_width=$image_width/$height_ratio;
    $dest_height=$height;
}

$int_width = ($width - $dest_width)/2;
$int_height = 0;

暂无
暂无

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

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