php生成缩略图封装

<?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'));

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值