我正在寻找帮助/建议,以找到使用PHP/GD将图像调整为尽可能小的最有效方法,同时保留原始图像的纵横比,但确保调整后的图像大于定义的最小宽度& 高度。
例如,调整大小的图像必须具有>= 400 的宽度和 >= 300 的高度,但应在保持原始纵横比的同时尽可能接近这些尺寸。
这样,“风景”图像的理想高度为 300或稍大,宽度 >= 400,“人像”图像的理想宽度为 400或稍大,高度 >= 300。
我正在寻找帮助/建议,以找到使用PHP/GD将图像调整为尽可能小的最有效方法,同时保留原始图像的纵横比,但确保调整后的图像大于定义的最小宽度& 高度。
例如,调整大小的图像必须具有>= 400 的宽度和 >= 300 的高度,但应在保持原始纵横比的同时尽可能接近这些尺寸。
这样,“风景”图像的理想高度为 300或稍大,宽度 >= 400,“人像”图像的理想宽度为 400或稍大,高度 >= 300。
我相信这就是您正在寻找的;具体来说,中间一栏的图片:
下面的代码是从Crop-To-Fit an Image Using ASP/PHP派生的:
list(
$source_image_width,
$source_image_height
) = getimagesize( '/path/to/image' );
$target_image_width = 400;
$target_image_height = 300;
$source_aspect_ratio = $source_image_width / $source_image_height;
$target_aspect_ratio = $target_image_width / $target_image_height;
if ( $target_aspect_ratio > $source_aspect_ratio )
{
// if target is wider compared to source then
// we retain ideal width and constrain height
$target_image_height = ( int ) ( $target_image_width / $source_aspect_ratio );
}
else
{
// if target is taller (or has same aspect-ratio) compared to source then
// we retain ideal height and constrain width
$target_image_width = ( int ) ( $target_image_height * $source_aspect_ratio );
}
// from here, use GD library functions to resize the image
这似乎完成了工作......
$data = @getimagesize($image);
$o_w = $data[0];
$o_h = $data[1];
$m_w = 400;
$m_h = 300;
$c_w = $m_w / $o_w;
$c_h = $m_h / $o_h;
if($o_w == $o_h){
$n_w = ($n_w >= $n_h)?$n_w:$n_h;
$n_h = $n_w;
} else {
if( $c_w > $c_h ) {
$n_w = $m_w;
$n_h = $o_h * ($n_w/$o_w);
} else {
$n_h = $m_h;
$n_w = $o_w * ($n_h/$o_h);
}
}