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

PHP开发学习笔记之生成缩略图

2017-02-19 15:48 549 查看

使用GD库生成图片的缩略图

1.函数名及参数属性展示

function resizeImage($filename, $destination=null, $dst_w=null, $dst_h=null, $isReserved=true, $scale=0.5)


其中,filename保存的上传图片的名称,destination指保存的路径(目录+文件名),默认为空,dst_w、dst_h分别是目标图像画布的宽、高,默认为null。isReserved标识符决定了是否保留上传图片,scale保存了图片的缩放比例。

2.首先获取源图片的宽高、类型等信息

list($src_w, $src_h, $src_type) = getimagesize($filename);


getimagesize函数返回指定文件的尺寸、类型,如果不能访问指定文件或不是有效的图像将返回false(在判断上传文件是否是真的图片类型时将相当有效)。

3.获取图片的MIME类型,并进行相关字符串操作

//图片的MIME:image/gif, image/jpg
$mime = image_type_to_mime_type($src_type);
$createFun = str_replace("/", "createfrom", $mime);
$outFun = str_replace("/", null, $mime);


imagecreatefromgif,imagecreatefromjpg函数通过文件名创建图像,其中的createfrom固定不变,可通过字符串操作将MIME中的“/”替换为”createfrom”得到createFun,将MIME中的“/”替换为null得到输出函数outFun。

4.创建源画布、目标画布并进行画布融合

//创建源画布
$src_img = $createFun($filename);
//目标画布宽、高
$dst_img = imagecreatetruecolor($dst_w, $dst_h);
//画布融合
imagecopyresampled($dst_img, $src_img, 0, 0, 0, 0, $dst_w, $dst_h, $src_w, $src_h);


5.判断目标文件目录是否存在

if($destination && !file_exists(dirname($destination))){
mkdir(dirname($destination), 0777, true);
}
//如果$destination为空则给它赋值
$des_name = $destination == null ?  getUniName().".".getExt($filename) : $destination;


6.显示并保存图像,删除画布并判断是否删除原文件

$outFun($dst_img, $des_name);
imagedestroy($dst_img);
imagedestroy($src_img);
//删除原文件
if(!$isReserved){
unlink($filename);
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: