//封装一个函数,用于返回图像信息
function getImageInfo($filename){
//检测$filename是否是一个图片
if (!$info = getimagesize($filename)){
exit('文件不是真实图片!');//或者直接返回false
}
//将得到的图片各种信息保存在数组里面
//得到图片的宽高和类型
$fileInfo['width'] = $info[0];
$fileInfo['height'] = $info[1];
$mime = $info['mime'];
//自带函数得到类型
// $mime = image_type_to_mime_type($info[2]);
//使用$mime替换成可用函数
$create = str_replace('/','createfrom',$mime);//创建画布资源
$outimage = str_replace('/',null,$mime);//保存图像类型
$latename = strtolower(image_type_to_extension($info[2]));//得到图片后缀名
$fileInfo['resource'] = $create;
$fileInfo['output'] = $outimage;
$fileInfo['ext'] = $latename;
//返回数组
return $fileInfo;
}
//封装成生成缩略图的函数
function thumb($filename,$dest = '../thumb/',$pre = 'thumb',$destdel = false,
$dst_w = 200,$dst_h=139){
//图片路径
// $filename = '../Public/Image/12.jpg';
//调用函数,得到图片信息
$imaheInfon = getImageInfo($filename);
//图片缩放分两种情况
//$scale = 0.5;//设置比例缩放为一半,没有设置最大宽高
//设置了最大宽高,按等比例算法来做
//$dst_w = 200;
//$dst_h = 150;
//得到原图像的宽高
$src_w = $imaheInfon['width'];
$src_h = $imaheInfon['height'];
/**使用if判断$dst_w 、$dst_h是否设置了宽高,is_numeric() 函数用于判断
* 检测变量是否为数字或数字字符串,为真返回 TRUE,否则返回 FALSE
*
*/
if(is_numeric($dst_w)&&is_numeric($dst_h)){
//设置了最大宽高,按等比例算法来做
$ratio_orig = $src_w/$src_h;
if ($dst_w/$dst_h > $ratio_orig){
$dst_w =$dst_h*$ratio_orig;
}else{
$dst_h = $dst_w/$ratio_orig;
}
}else{
//设置比例缩放为一半,没有设置最大宽高
$dst_w =ceil( $src_w*$scale);//ceil()取整
$dst_h =ceil( $src_h*$scale);
}
//创建画布资源
$dst_image = imagecreatetruecolor($dst_w,$dst_h);
//$src_image = imagecreatetruecolor($src_w,$src_h);
$src_image = $imaheInfon['resource']($filename);
//生成缩略图
imagecopyresampled($dst_image,$src_image,0,0,0,0,
$dst_w,$dst_h,$src_w,$src_h);
//指定保存路径
// $dest = '../thumb/';
//判断目录是否存在,不存在则创建,file_exists() 函数检查文件或目录是否存在
if ($dest && !file_exists($dest)){
//mkdir() 函数创建目录
mkdir($dest,0777,true);
}
//防止重名产生覆盖,可定义一个前缀,再拼上一个随机数
// $pre = 'thumb';
$randNum = mt_rand(1000,9999);
$destname ="{$pre}_{$randNum}".$imaheInfon['ext'];//文件名
$destination = $dest ? $dest.'/'.$destname:$destname;//判断文件路径
$imaheInfon['output']($dst_image,$destination);//保存文件到路径
return $destination;//返回文件路径
//是否删除源文件
// $destdel = false;//设置默认为false
if ($destdel){
unlink($filename);//删除文件
}
//销毁资源
imagedestroy($dst_image);
imagedestroy($src_image);
}
$filename = '../Public/Image/11.jpg';
thumb($filename);