首先介绍一个PHP上传图片缩略图的方法:
 
function CreatePreview($img,$name,$path,$maxwidth,$maxheight,$quality){//图片,保存名称,保存路径,最大宽,最大高,质量
 $widthratio=0;
 $heightratio=0;
 $width=p_w_picpathsx($img);
 $height=p_w_picpathsy($img);
 //开始计算缩小比例
 if($width>$maxwidth||$height>$maxheight){
  if($width>$maxwidth){
   $widthratio=$maxwidth/$width;
  }
  if($height>$maxheight){
   $heightratio=$maxheight/$height;
  }
  if($widthratio>0&&$heightratio>0){
   if($widthratio<$heightratio){
    $ratio=$widthratio;
   }else{
    $ratio=$heightratio;
   }
  }elseif($widthratio>0){
   $ratio=$widthratio;
  }elseif($heightratio>0){
   $ratio=$heightratio;
  }
  //根据得出的比例,重新计算缩略图的宽和高
  $newwidth=$ratio*$width;
  $newheight=$ratio*$height;
  $newimg=p_w_picpathcreatetruecolor($newwidth,$newheight); // 创建目标图
  p_w_picpathcopyresized($newimg,$img,0,0,0,0,$newwidth,$newheight,$width,$height);
  ImageJpeg($newimg,$path."s_".$name,$quality);
  Imagedestroy($newimg);
 }else{
  ImageJpeg($img,$path."s_".$name,$quality);
 }
}
 
其中创建目标图一句,如果使用普通的p_w_picpathcreate()函数将造成图片质量失真的情况,从网上搜了一下解决办法,方法是用p_w_picpathcreateruecolor()函数替换p_w_picpathcreate()函数。
p_w_picpathcreateruecolor()函数用法(引自PHP手册):
 
resource p_w_picpathcreatetruecolor ( int x_size, int y_size)
例子 1. 新建一个新的 GD 图像流并输出图像
header ("Content-type: p_w_picpath/png");
$im = @p_w_picpathcreatetruecolor (50, 100
)
     or die (
"Cannot Initialize new GD p_w_picpath stream"
);
$text_color = p_w_picpathcolorallocate ($im, 233, 14, 91
);
p_w_picpathstring ($im, 1, 5, 5"A Simple Text String", $text_color
);
p_w_picpathpng ($im
);
p_w_picpathdestroy ($im
);
?>

例如原图:
PHP上传真彩图片缩略图质量失真解决方法_第1张图片
 
使用p_w_picpathcreate()函数创建后的缩略图:
 
使用p_w_picpathcreateruecolor()函数创建后的缩略图:
 
注:
 
  p_w_picpathcreateruecolor()函数要看服务器上PHP和GD库的版本而定,PHP手册上明确写出p_w_picpathcreateruecolor()函数添加于 PHP 4.0.6 并需要 GD 2.0.1 或更高版本支持。