Aut*_*one 1 php gd resize image aspect-ratio
我正在寻找帮助/建议找到最有效的方法来调整图像的大小尽可能小使用PHP/GD,同时保留原始图像的宽高比,但确保调整大小的图像大于定义的最小宽度和身高.
例如,调整大小的图像必须具有宽度> = 400且高度> = 300但应尽可能接近这些尺寸,同时保持原始高宽比.
这样"景观"图像的理想高度为300或稍大,宽度> = 400,"肖像"图像的理想宽度为400或稍大,高度> = 300.
我相信这就是你要找的东西; 具体来说,中间栏中的图片:

以下代码使用ASP/PHP从Crop-To-Fit图像派生:
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
Run Code Online (Sandbox Code Playgroud)