如何高效生成缩略图?
如何高效生成缩略图?我用php写了一个,感觉效率不怎么高:
function MakeBuild($BuildFile,$newFile,$File_width,$File_height=0,$rate=1000) {
if(!is_file($BuildFile)){
$this->msg("文件 ".$BuildFile." 不是一个有效的图形文件!nn系统无法生成该文件的缩略图!");
return false;
}
$data = GetImageSize($BuildFile);
switch($data[2]){
case 1:
$im = @ImageCreateFromGIF($BuildFile);
break;
case 2:
$im = @ImageCreateFromJPEG($BuildFile);
break;
case 3:
$im = @ImageCreateFromPNG($BuildFile);
break;
}
if(!$im){
return false;
}
else{
$srcW = ImageSX($im); # 取得原图宽度;
$srcH = ImageSY($im); # 取得原图高度;
$dstX = 0;
$dstY = 0;
if($File_height==0){
$File_height = $File_width/$srcW*$srcH;
}
if ($srcW*$File_height>$srcH*$File_width){
$fFile_height = round($srcH*$File_width/$srcW);
$dstY = floor(($File_height-$fFile_height)/2);
$fFile_width = $File_width;
}
else {
$fFile_width = round($srcW*$File_height/$srcH);
$dstX = floor(($File_width-$fFile_width)/2);
$fFile_height = $File_height;
}
$ni = ImageCreateTrueColor($File_width,$File_height);
$dstX = ($dstX<0)?0:$dstX;
$dstY = ($dstX<0)?0:$dstY;
$dstX = ($dstX>($File_width/2))?floor($File_width/2):$dstX;
$dstY = ($dstY>($File_height/2))?floor($File_height/s):$dstY;
ImageCopyResized($ni,$im,$dstX,$dstY,0,0,$fFile_width,$fFile_height,$srcW,$srcH);
ImageJpeg($ni,$newFile,$rate); # 生成缩略图;
imagedestroy($im); # imagedestroy(resource) 释放image关联的内存
}
}
//MakeBuild('DSC_0542.JPG',"suo/DSC_0542.JPG","100");
绯色的兔子先生
12 years, 7 months ago
Answers
兼容gd1.6和gd2.x
function ImageResize($srcFile,$toW,$toH,$toFile="")
{
if($toFile==""){ $toFile = $srcFile; }
$info = "";
$data = GetImageSize($srcFile,$info);
switch ($data[2])
{
case 1:
if(!function_exists("imagecreatefromgif")){
echo "你的GD库不能使用GIF格式的图片,请使用Jpeg或PNG格式!<a href='javascript:go(-1);'>返回</a>";
exit();
}
$im = ImageCreateFromGIF($srcFile);
break;
case 2:
if(!function_exists("imagecreatefromjpeg")){
echo "你的GD库不能使用jpeg格式的图片,请使用其它格式的图片!<a href='javascript:go(-1);'>返回</a>";
exit();
}
$im = ImageCreateFromJpeg($srcFile);
break;
case 3:
$im = ImageCreateFromPNG($srcFile);
break;
}
$srcW=ImageSX($im);
$srcH=ImageSY($im);
$toWH=$toW/$toH;
$srcWH=$srcW/$srcH;
if($toWH<=$srcWH){
$ftoW=$toW;
$ftoH=$ftoW*($srcH/$srcW);
}
else{
$ftoH=$toH;
$ftoW=$ftoH*($srcW/$srcH);
}
if($srcW>$toW||$srcH>$toH)
{
if(function_exists("imagecreatetruecolor")){
@$ni = ImageCreateTrueColor($ftoW,$ftoH);
if($ni) ImageCopyResampled($ni,$im,0,0,0,0,$ftoW,$ftoH,$srcW,$srcH);
else{
$ni=ImageCreate($ftoW,$ftoH);
ImageCopyResized($ni,$im,0,0,0,0,$ftoW,$ftoH,$srcW,$srcH);
}
}else{
$ni=ImageCreate($ftoW,$ftoH);
ImageCopyResized($ni,$im,0,0,0,0,$ftoW,$ftoH,$srcW,$srcH);
}
if(function_exists('imagejpeg')) ImageJpeg($ni,$toFile);
else ImagePNG($ni,$toFile);
ImageDestroy($ni);
}
ImageDestroy($im);
}
GP02POI
answered 12 years, 7 months ago