我使用以下方法调整图像大小:
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);
}
之后我想保存这张图片。对于这种情况,我使用这种方法:
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);
}
当我保存尺寸为300x300到240x240的图像时,新图像的质量非常差。哪里我错了?
图片: