Please i am using the below php image function to resize image when uploading or while displaying the image on page, but i found out that when i tried to resize an original image it doesn't give me the actual dimension that i want.
Example: the original image width is 600
and height is 400
I intend to resize it to 180 X 180
, but it gave me width 180
and height 120
. Please i don't know what the problem is can anyone help?
<?php
function CroppedThumbnail($imagename, $meta, $newpath, $imgwidth, $imgheight, $rename, $imgQuality){
// Set a maximum height and width
$width = $imgwidth;
$height = $imgheight;
$url = '';
//Get image info
$info = @getimagesize($imagename);
$fileparts = pathinfo($imagename);
// Get new dimensions
$imageAvatar = substr($fileparts['filename'],0,5) . '-' . $imgwidth . 'x' . $imgheight . '.png';
if(is_dir($newpath . '/') && file_exists($newpath . '/' . $imageAvatar)){
return $url . $newpath . '/' . $imageAvatar;
}else{
list($width_orig, $height_orig) = $info;
$ratio_orig = $width_orig/$height_orig;
if ($width/$height > $ratio_orig) {
$width = $height*$ratio_orig;
} else {
$height = $width/$ratio_orig;
}
// Resample
if ($info['mime'] == 'image/jpeg'){
$image = imagecreatefromjpeg($url.$imagename);
}
else if ($info['mime'] == 'image/gif'){
$image = imagecreatefromgif($url.$imagename);
}
else if ($info['mime'] == 'image/png'){
$image = imagecreatefrompng($url.$imagename);
}
$image_p = imagecreatetruecolor($width, $height);
imagecopyresampled($image_p, $image, 0, 0, 0, 0, $width, $height, $width_orig, $height_orig);
//Rename the image
if($rename == true){
$newName = substr($fileparts['filename'],0,5) . '-' . $imgwidth . 'x' . $imgheight;
$newFileName = $newpath . '/' . $newName . '.png';
}else{
$newFileName = $newpath . '/' . $imagename;
}
// Output
imagejpeg($image_p, $newFileName, $imgQuality);
return $url . $newFileName;
}
}
This because you are keeping the original aspect ratio of the image.
This is in the following line of code:
$ratio_orig = $width_orig/$height_orig;
if ($width/$height > $ratio_orig) {
$width = $height*$ratio_orig;
} else {
$height = $width/$ratio_orig;
}
If you don't want to keep the aspect ration just delete those lines.