I using following method to resize image:
private function newDim($maxHeight, $maxWidth, $height, $width) {
if(($width / $height) >= ($maxWidth / $maxHeight)){
$nw = $maxWidth;
$nh = $height * ($maxWidth / $width);
$nx = round(abs($maxHeight - $nh) / 2);
$ny = 0 ;
}else {
// by height
$nw = $width*($maxHeight/$height);
$nh = $maxHeight;
$nx = 0;
$ny = round(abs($maxWidth - $nw) / 2); ;
}
return array($nw,$nh,$nx,$ny);
}
After that I want to save this image. For this case I using this method:
public function upload($file_param_name) {
$file_name = $_FILES[$file_param_name]['name'];
$source_file_path = $_FILES[$file_param_name]['tmp_name'];
$$this->ext = pathinfo($file_name, PATHINFO_EXTENSION);
$ext = 'jpg';
$this->ext = $ext;
$ext =strtolower($ext);
$new_file_name = $file_name."-".md5(uniqid(rand(), true));
$this->image_hashname = $new_file_name;
$target_path = $this->store_folder.basename($new_file_name);
list($width,$height,$type)=getimagesize($source_file_path);
switch ($type) {
case 1: // gif -> jpg
$src = imagecreatefromgif($source_file_path);
break;
case 2: // jpeg -> jpg
$src = imagecreatefromjpeg($source_file_path);
break;
case 3: // png -> jpg
$src = imagecreatefrompng($source_file_path);
break;
}
$th = 240;
$tw = 240;
list($nh,$nw,$nx,$ny) = $this->newDim($th, $tw, $height, $width);
$tmp=imagecreatetruecolor($tw,$th);
$white = imagecolorallocate($tmp, 255,255,255);
imagefill($tmp, 0, 0, $white);
imagecopyresized($tmp,$src,$ny,$nx,0,0,$nh,$nw,$width,$height);
$thmbfile = $this->store_folder.basename($new_file_name."-thumb.".$ext);
imagejpeg($tmp,$thmbfile,100);
imagedestroy($src);
imagedestroy($tmp);
}
When I save image with sizes 300x300 to 240x240 the quality of new image is very poor. Where I'm wrong?
The images :