Reputation: 8369
I am trying to resize an image to a width of 500px. I want to keep the aspect ratio of the image.
My original image is
When I resized it to size of width 500, it is coming like
I am doing the following code for resizing image.
$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);
With this code, the width is changed to 500px but height is not proportional. What I am doing wrong? Can anyone help me to fix it?
Thanks in advance
Upvotes: 0
Views: 120
Reputation: 2510
You're calculating the ratio incorrectly. Instead of dividing the new width by the original height, you want something like this:
list($w, $h) = getimagesize($target_dir);
$width = 500;
$ratio = $w / $h;
$height = $width / $ratio;
Upvotes: 2