用保留质量的php调整图片大小
Posted
技术标签:
【中文标题】用保留质量的php调整图片大小【英文标题】:Resizing pictures with preserving quality php 【发布时间】:2012-09-03 13:02:48 【问题描述】:我使用以下方法调整图像大小:
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 的图像时,新图像的质量很差。我哪里错了?
图片:
旧:http://cbn-design.eu/imgs/original.jpg
新:http://cbn-design.eu/imgs/new.jpg
【问题讨论】:
你能用 ImageMagick 代替吗?看到这个问题:ImageMagick vs GD - which is faster, less resource intensive and produces better images? 【参考方案1】:根据this answer,尝试使用imagecopyresampled()
而不是imagecopyresized()
。
【讨论】:
以上是关于用保留质量的php调整图片大小的主要内容,如果未能解决你的问题,请参考以下文章