php使用GD创建保持宽高比缩略图的方法
本文实例讲述了php使用GD创建保持宽高比缩略图的方法。分享给大家供大家参考。具体如下:
/**
*Createathumbnailimagefrom$inputFileNamenotallerorwiderthan
*$maxSize.Returnsthenewimageresourceorfalseonerror.
*Author:mthorn.net
*/
functionthumbnail($inputFileName,$maxSize=100)
{
$info=getimagesize($inputFileName);
$type=isset($info['type'])?$info['type']:$info[2];
//Checksupportoffiletype
if(!(imagetypes()&$type))
{
//Serverdoesnotsupportfiletype
returnfalse;
}
$width=isset($info['width'])?$info['width']:$info[0];
$height=isset($info['height'])?$info['height']:$info[1];
//Calculateaspectratio
$wRatio=$maxSize/$width;
$hRatio=$maxSize/$height;
//Usingimagecreatefromstringwillautomaticallydetectthefiletype
$sourceImage=imagecreatefromstring(file_get_contents($inputFileName));
//Calculateaproportionalwidthandheightnolargerthanthemaxsize.
if(($width<=$maxSize)&&($height<=$maxSize))
{
//Inputissmallerthanthumbnail,donothing
return$sourceImage;
}
elseif(($wRatio*$height)<$maxSize)
{
//Imageishorizontal
$tHeight=ceil($wRatio*$height);
$tWidth=$maxSize;
}
else
{
//Imageisvertical
$tWidth=ceil($hRatio*$width);
$tHeight=$maxSize;
}
$thumb=imagecreatetruecolor($tWidth,$tHeight);
if($sourceImage===false)
{
//Couldnotloadimage
returnfalse;
}
//Copyresampledmakesasmooththumbnail
imagecopyresampled($thumb,$sourceImage,0,0,0,0,$tWidth,$tHeight,$width,$height);
imagedestroy($sourceImage);
return$thumb;
}
/**
*Savetheimagetoafile.Typeisdeterminedfromtheextension.
*$qualityisonlyusedforjpegs.
*Author:mthorn.net
*/
functionimageToFile($im,$fileName,$quality=80)
{
if(!$im||file_exists($fileName))
{
returnfalse;
}
$ext=strtolower(substr($fileName,strrpos($fileName,'.')));
switch($ext)
{
case'.gif':
imagegif($im,$fileName);
break;
case'.jpg':
case'.jpeg':
imagejpeg($im,$fileName,$quality);
break;
case'.png':
imagepng($im,$fileName);
break;
case'.bmp':
imagewbmp($im,$fileName);
break;
default:
returnfalse;
}
returntrue;
}
$im=thumbnail('temp.jpg',100);
imageToFile($im,'temp-thumbnail.jpg');
希望本文所述对大家的php程序设计有所帮助。