我正在尝试将图像调整为500px的宽度。我想保持图像的宽高比。
我的原始图片是
当我将其大小调整为宽度500时,它就像
我正在执行以下代码来调整图像大小。
$target_dir="uploads/reference/".$data['CP_Image'];
move_uploaded_file($tmp_file, $target_dir);
list($w, $h) = getimagesize($target_dir);
$width=500;
$ratio = $width / $h;
$x = ($w - $width / $ratio) / 2;
$height = 500 / $ratio;exit;
$path = "uploads/reference/".$data['CP_Image'];
$thumb = imagecreatetruecolor($width, $height);
$source = imagecreatefromjpeg($target_dir);
// Resize
imagecopyresized($thumb, $source, 0, 0, 0, 0, $width, $height, $w, $h);
// Output and free memory
imagejpeg($thumb,$path);
imagedestroy($thumb);
使用此代码,宽度更改为500px,但高度不成比例。我做错了什么?有人可以帮我解决吗?
提前致谢
答案 0 :(得分:2)
您未正确计算比率。不要将新宽度除以原始高度,而是需要这样的东西:
list($w, $h) = getimagesize($target_dir);
$width = 500;
$ratio = $w / $h;
$height = $width / $ratio;