您的位置:首页 > 编程语言 > PHP开发

PHP生成缩略图

2017-07-29 15:37 309 查看
/**
* 生成唯一字符串
* @return string
*/
function getUniName(){
return md5(uniqid(microtime(true),true));
}

/**
* 得到文件的扩展名
* @param string $filename
* @return string
*/
function getExt($filename){
return strtolower(end(explode(".",$filename)));
}

/**
* 生成缩略图
* @param string $filename
* @param string $destination
* @param int $dst_w
* @param int $dst_h
* @param bool $isReservedSource
* @param number $scale
* @return string
*/
function thumb($filename,$destination=null,$dst_w=null,$dst_h=null,$isReservedSource=true,$scale=0.5){
//默认不保留源文件$isReservedSource=false
list($src_w,$src_h,$imagetype)=getimagesize($filename);
if(is_null($dst_w)||is_null($dst_h)){
$dst_w=ceil($src_w*$scale);
$dst_h=ceil($src_h*$scale);
}
$mime=image_type_to_mime_type($imagetype);
//echo $mime;//image/jpeg,image/gif
$createFun=str_replace("/", "createfrom", $mime);//imagecreatefromjpeg
$outFun=str_replace("/", null, $mime);//imagejpeg
$src_image=$createFun($filename);
$dst_image=imagecreatetruecolor($dst_w, $dst_h);
imagecopyresampled($dst_image, $src_image, 0,0,0,0, $dst_w, $dst_h, $src_w, $src_h);
if($destination&&!file_exists(dirname($destination))){
mkdir(dirname($destination),0777,true);
}
$dstFilename=$destination==null?getUniName().".".getExt($filename):$destination;
$outFun($dst_image,$dstFilename);
imagedestroy($src_image);//销毁资源
imagedestroy($dst_image);//销毁资源
if(!$isReservedSource){
unlink($filename);//删掉源文件
}
return $dstFilename;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: