从顶部裁剪,而不是从中心裁剪

Crop from top, not from center

我有一个从中心裁剪图像的脚本,有没有办法让它从图像的顶部裁剪?我尝试这样做,但我只是弄乱了代码。

裁剪脚本如下:

if($crop){
    $new_image = imagecreatetruecolor($width, $height);

    if($current_ratio > $desired_ratio_after){
        $new_width = $old_width * $height / $old_height;
    }

    if($current_ratio > $desired_ratio_before && $current_ratio < $desired_ratio_after){
        if( $old_width > $old_height ){
            $new_height = max( $width, $height );
            $new_width = $old_width * $new_height / $old_height;
        }
        else{
            $new_height = $old_height * $width / $old_width;
        }
    }

    if($current_ratio < $desired_ratio_before){
        $new_height = $old_height * $width / $old_width;
    }

    $width_ratio = $old_width / $new_width;
    $height_ratio = $old_height / $new_height;

    $src_x = floor( ( ( $new_width - $width ) / 2 ) * $width_ratio );
    $src_y = round( ( ( $new_height - $height ) / 2 ) * $height_ratio );
}

我假设您不想从顶部裁剪(这意味着移除顶部),而是裁剪以保留顶部?然后我很确定通过设置 $src_y = 0 将意味着占据顶部。

如果你想从顶部裁剪,意思是只保留底部,那么可能 $src_y = $old_height - $new_height 就可以了。

所有这些假设 $src_y 是原始图像中的起始 Y 坐标。