我正在尝试使用@imagecopyresampled
调整大小和裁剪图像,保持原始纵横比。
思路如下: 1)我固定缩略图的一个维度(例如300x40) 2)从高度中心开始裁剪
我尝试阅读文档和stackoverflow上的许多其他问题,但没有结果。 有人可以帮帮我吗?? 我目前的代码如下:
//$img_height, $img_width [original size of the image]
$thumb_width = 300;
$thumb_height = 40;
$new_img = @imagecreatetruecolor($thumb_width, $thumb_height);
$middle = floor($img_height/2);
$src_x = 0;
$src_y = $middle-($thumb_width/2);
$src_w = $img_width;
$aspectRatio = $img_width/$thumb_width;
//$src_h = ?????
$imgCopyRes = @imagecopyresampled(
$new_img, $src_img,
0, 0,
$src_x, $src_y,
$thumb_width, $thumb_height,
$src_w, $src_h);
编辑:
非常感谢 @Joshua Burns,通过阅读你的类和编辑你的代码,我已经找到了解决方案,而不需要包含整个文件。
代码:
$target_width = 300;
$target_height = 40;
$new_img = @imagecreatetruecolor($target_width, $target_height);
$width_ratio = $target_width / $img_width;
$height_ratio = $target_height / $img_height;
if($width_ratio > $height_ratio) {
$resized_width = $target_width;
$resized_height = $img_height * $width_ratio;
} else {
$resized_height = $target_height;
$resized_width = $img_width * $height_ratio;
}
// Drop decimal values
$resized_width = round($resized_width);
$resized_height = round($resized_height);
// Calculations for centering the image
$offset_width = round(($target_width - $resized_width) / 2);
$offset_height = round(($target_height - $resized_height) / 2);
$imgCopyRes = @imagecopyresampled(
$new_img, $src_img,
$offset_width, $offset_height,
0, 0,
$resized_width, $resized_height,
$img_width, $img_height);