使用ThinkPHP5可以方便地动态生成缩略图,从而减少网站流量消耗

2023-12-07 0 963

前言:

使用动态处理可以节省流量,但由于是使用PHP处理,会造成一点点的物理损耗(可以忽略不计)。
使用ThinkPHP5可以方便地动态生成缩略图,从而减少网站流量消耗


# 使用 composer 安装 think扩展类
composer require topthink/think-image

由于 tp5 自带图片处理类,我们不需要再额外编写裁剪等方法。但是 tp5 的图片处理类没有输出方法,我们可以复制一份 save 方法,并命名为 preview 方法,稍作修改以用于输出。(该类文件的路径为 vendor/topthink/think-image/src/Image.php,如果没有该类文件,请使用 composer 下载。)代码如下:


public function preview($quality = 100, $interlace = true)
    {
 
        $type = $this->info['type'];
        header('content-type:'.$this->info['mime']);
        if ('jpeg' == $type || 'jpg' == $type) {
            //JPEG 图像设置隔行扫描
            imageinterlace($this->im, $interlace);
            imagejpeg($this->im, null, $quality);
        } elseif ('gif' == $type && !empty($this->gif)) {
            imagegif($this->im, null);
        } elseif ('png' == $type) {
            //设定保存完整的 alpha 通道信息
            imagesavealpha($this->im, true);
            //ImagePNG 生成图像的质量范围从 0 到 9 的
            imagepng($this->im, null, min((int) ($quality / 10), 9));
        } else {
            $fun = 'image' . $type;
            $fun($this->im, '');
        }
        exit; //一定要写 exit,不然输出的是二进制代码
    }

我们随意创建一个控制器和一个方法,例如:Image/thumb,调用刚刚我们修改的方法,代码如下:


public function thumb($path,$width=160,$height=120)
{
    $image = \think\Image::open(trim($path,'/'));
   #居中方式裁剪(更多请看 Image 类)
    $image->thumb($width,$height,3)->preview();
}

服务端配置


#Apache 配置
<IfModule mod_rewrite.c>
    Options +FollowSymlinks -Multiviews
    RewriteEngine On
    
    #新增配置
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteRule ^(.+\.(jpg|jpeg|png|gif))!(\d+)x(\d+).*$ image/thumb?path=$1&width=$3&height=$4
    #新增配置
    
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteRule ^(.*)$ index.php/$1 [QSA,PT,L]
</IfModule>
 
 
 
#Nginx 配置
 
if (!-e $request_filename) {
    #新增配置
    rewrite  ^(.+\.(jpg|jpeg|png|gif))!(\d+)x(\d+).*$ image/thumb?path=$1&width=$3&height=$4;
    #新增配置
    rewrite  ^(.*)$  /index.php?s=$1  last;
    break;
}

访问:http://xxxx.com/Image/thumb?path=test.jpg&width=320&height=240

在进行图片上传时,通常会生成一张缩略图。这样做的好处是在客户端获取图片时可以更快地加载图片数据,并且可以减少服务器的带宽请求。

传统的做法是在上传图片时生成一张缩略图,但是这种做法有两个缺点。首先,会占用服务器的存储空间;其次,无法随意更改缩略图的大小。

因此,我们需要一个能够动态修改缩略图的解决方案。

本文章已结束,如转载请注明:汇站网 » 使用 ThinkPHP5 可以方便地动态生成缩略图,从而减少网站流量消耗

收藏 (0)

微信支付 微信扫一扫

支付宝支付 支付宝扫一扫

打赏二维码
点赞 (0)

站长资源下载中心-找源码上汇站

常见问题
  • 如果付款后没有弹出下载页面,多刷新几下,有问题联系客服!
查看详情
  • 本站所有资源版权均属于原作者所有,这里所提供资源均只能用于参考学习用,请勿直接商用。若由于商用引起版权纠纷,一切责任均由使用者承担。
查看详情

相关文章

联系官方客服

为您解决烦忧 - 24小时在线 专业服务