<?php
/**
* 缩略图实现封装
* @param string $file_name 源图片路径
* @param int $type 缩略方式(1等比例缩放,2在限制宽高大小内实现等比例,默认为1)
* @param int $percent 缩放比例(type为1时可选参数,0.1-4,默认为1)
* @param int $dst_w 限制最大宽(type为2可选参数,默认100,10-1000)
* @param int $dst_h 限制最大高 (type为2可选参数,默认100,10-1000)
* @param string $save_path 缩略图保存位置
*/
function thumbImageFun($file_name = '', $type = 1, $percent = 1, $dst_w = 100, $dst_h = 100, $save_path = '')
{
//源图片信息
if (!is_file($file_name)) {
return '未找到文件';
}
@$file_info = getimagesize($file_name);
if (!$file_info) {
return '不是真实图片';
}
if(!in_array($type,[1,2])){
return '缩略方式选择有误';
}
list($src_w, $src_h) = $file_info;//图片尺寸
$mime = $file_info['mime'];//图片类型 类似image/png
$createFun = str_replace('/', 'createfrom', $mime);//用变量创建替换函数,增加扩展性
$outFun = str_replace('/', null, $mime);//用变量创建替换函数,增加扩展性
$src_image = $createFun($file_name);//生成资源句柄,函数用动态变量替换 imagecreatefrompng()
//等比例缩放
if ($type == 1) {
if ($percent < 0.1 || $percent > 5){
return '缩放比例超过限制范围';
}
//目标缩略图信息
$dst_w = $src_w * $percent;
$dst_h = $src_h * $percent;
}
//在限制大小内实现等比例缩放
if($type == 2){
if ($dst_w < 10 || $dst_w > 1000 || $dst_h < 10 || $dst_h > 1000) {
return '缩放宽高超过限制范围';
}
$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;
}
}
$dst_image = imagecreatetruecolor($dst_w, $dst_h);//生成目标资源句柄
//生成缩略图
imagecopyresampled($dst_image, $src_image, 0, 0, 0, 0, $dst_w, $dst_h, $src_w, $src_h);
header("Content-type: $mime");//用动态变量替换
$outFun($dst_image);//函数用动态变量替换 imagepng(),输出到浏览器
if($save_path && !empty($save_path)){
if(!file_exists($save_path)){
mkdir($save_path,0777,true);
}
$outFun($dst_image,$save_path.'/'.'thumb_'.substr(md5(uniqid(microtime(true),true)),0,5).basename($file_name));//函数用动态变量替换 imagepng(),保存进文件
}
//销毁资源句柄
imagedestroy($src_image);
imagedestroy($dst_image);
}
print_r(thumbImageFun('../image/2.jpeg',2,0.2,400,400,'thumb'));
php生成缩略图封装
最新推荐文章于 2021-03-23 11:00:42 发布
本文介绍了一种使用PHP实现的图片缩略图生成方法,包括等比例缩放和在限制宽高内实现等比例缩放两种方式。通过动态创建图片处理函数,增加了代码的扩展性和灵活性。
123

被折叠的 条评论
为什么被折叠?



