首先介绍一个PHP上传图片缩略图的方法:
function CreatePreview($img,$name,$path,$maxwidth,$maxheight,$quality){//图片,保存名称,保存路径,最大宽,最大高,质量
$widthratio=0;
$heightratio=0;
$width=imagesx($img);
$height=imagesy($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
$ratio=$widthratio;
}else{
$ratio=$heightratio;
}
}elseif($widthratio>0){
$ratio=$widthratio;
}elseif($heightratio>0){
$ratio=$heightratio;
}
//根据得出的比例,重新计算缩略图的宽和高
$newwidth=$ratio*$width;
$newheight=$ratio*$height;
$newimg=imagecreatetruecolor($newwidth,$newheight); // 创建目标图
imagecopyresized($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);
}
}
其中创建目标图一句,如果使用普通的imagecreate()函数将造成图片质量失真的情况,从网上搜了一下解决办法,方法是用imagecreateruecolor()函数替换imagecreate()函数。
imagecreateruecolor()函数用法(引自PHP手册):
resource imagecreatetruecolor ( int x_size, int y_size)
例子 1. 新建一个新的 GD 图像流并输出图像
header ("Content-type: image/png");
$im = @imagecreatetruecolor (50, 100)
or die ("Cannot Initialize new GD image stream");
$text_color = imagecolorallocate ($im, 233, 14, 91);
imagestring ($im, 1, 5, 5, "A Simple Text String", $text_color);
imagepng ($im);
imagedestroy ($im);
?>
例如原图:
使用imagecreate()函数创建后的缩略图:
使用imagecreateruecolor()函数创建后的缩略图:
注:
imagecreateruecolor()函数要看服务器上PHP和GD库的版本而定,PHP手册上明确写出imagecreateruecolor()函数添加于 PHP 4.0.6 并需要 GD 2.0.1 或更高版本支持。