首页 > 编程语言 >PHP批量压缩图片,基于TP5,fastadmin

PHP批量压缩图片,基于TP5,fastadmin

时间:2023-06-18 17:01:49浏览次数:49  
标签:fastadmin continue TP5 protected file time PHP base dir

<?php
/**
 * Created by PhpStorm.
 * User: zhuo <[email protected]>
 * O(∩_∩)O
 * Date: 2022-7-7 09:34:38
 */

namespace app\command;

use think\Image;
use think\image\Exception;
use think\console\{Command, Input, Output};

// 压缩图片
class CompressImg extends Command
{
    // 需处理的文件夹路径
    protected $base_dir = './public/upload/';

    // 排除文件夹
    protected $except_dirs = ['qrcode'];

    // 处理的图片类型
    protected $type = ['jpg', 'jpeg', 'png'];

    // 最宽
    protected $max_width = 960;

    // 最高
    protected $max_height = 960;

    // 图像质量
    protected $quality = 80;

    // 分配内存 1G
    protected $memory_limit = '1024M';

    // 只处理最后修改时间在多少时间内的文件,单位秒,0为不限制时间,默认1天
    protected $limit_time = 86400;

    protected function configure()
    {
        $this->setName('compress_img')->setDescription('压缩图片');
    }

    protected function execute(Input $input, Output $output)
    {
        // 防止文件过大,调大内存为1G
        ini_set('memory_limit', $this->memory_limit);
        $count      = 0;
        $start_time = time();
        dump('开始执行');
        $this->task($this->base_dir, $count);
        $end_time = time();
        dump('执行完成');
        printf("本次共处理文件数:%s。耗时:%s秒", $count, $end_time - $start_time);
    }

    protected function task($base_dir, &$count)
    {
        // 处理路径
        $base_dir = trim($base_dir, '/').'/';
        if (is_dir($base_dir)) {
            // 扫描文件
            $files = scandir($base_dir);
            // 迭代器
            foreach (yield_generate($files) as $file) {
                if (in_array($file, ['.', '..'])) {
                    continue;
                }
                // 重新组装文件路径
                $file = $base_dir.$file;
                // 文件夹 递归遍历
                if (is_dir($file)) {
                    // 排除文件夹
                    $filename = pathinfo($file)['filename'];
                    if (in_array($filename, $this->except_dirs)) {
                        continue;
                    }
                    // 递归
                    $this->task($file, $count);
                } else {
                    // 处理文件
                    if ($this->limit_time > 0) {
                        // 获取最后修改日期
                        $filemtime = filemtime($file);
                        clearstatcache();
                        if ( ! $filemtime) {
                            continue;
                        }
                        // 如果最后修改时间 大于限制时间 则不处理
                        if (time() - $filemtime >= $this->limit_time) {
                            continue;
                        }
                    }
                    // 商品下只压缩封面
                    // 路径包含goods
                    if (str_contains($file, 'goods/')) {
                        // 是否封面 商品下只压缩封面
                        if ( ! str_contains($file, 'cover')) {
                            continue;
                        }
                    }
                    // 是否图片,图片返回文件信息
                    if ( ! getimagesize($file)) {
                        continue;
                    }
                    try {
                        // 打开文件 忽略文件过大内存溢出
                        $image = @Image::open($file);
                        if ($image) {
                            // 返回图片的类型
                            $type = $image->type();
                            // 文件时图片 才进行压缩
                            if (in_array($type, $this->type)) {
                                // 压缩保存到原路径
                                $image->thumb($this->max_width, $this->max_height)->save($file, null, $this->quality, false);
                                $count++;
                                echo '.';
                            }
                        }
                    } catch (Exception $exception) {
                        printf("文件:%s,异常:%s", $file, $exception->getMessage());
                    }
                    // 释放内存
                    unset($image);
                }
            }
        }
    }
}

标签:fastadmin,continue,TP5,protected,file,time,PHP,base,dir
From: https://www.cnblogs.com/cn-oldboy/p/17489340.html

相关文章

  • Fastadmin会员管理-添加会员
    Fastadmin添加会员功能默认的框架没有这个功能,代码修改教程如下1.修改debug--/application/config.php修改成app_debug=true2.新增/application/admin/view/user/user/index.html文件修改,添加增加add按钮{:build_toolbar('refresh,add,edit,del')}3.新增/applicatio......
  • php函数array_filter的用法
    //array_filter()它用于筛选数组中的元素,并返回满足指定条件的元素//遍历数组中的每个元素,并将其传递给回调函数进行判断。//如果回调函数返回true,则该元素被保留在结果数组中;如果返回false,则该元素被过滤掉。//参数说明://$array:要筛选的数组。//$callback:一个回......
  • PHP中常用字符串函数
    //strlen取字符串长度$string="Hello,world!";$length=strlen($string);echo$length;//输出:13//strpos找字符串,返回位置$str="helloworld";$position=strpos($str,"world");echo$position;//输出:7//substr截取字符串$str=&quo......
  • xampp 发布 discuz(php6.5)
    1、xampp最新版本是php7.1 所以老版的 discuz(是php6.5)将最新xampp卸载,从下面地址下载xampp-win32-5.6.37-0-VC11-installer.exehttps://sourceforge.net/projects/xampp/files/XAMPP%20Windows/下载后安装好:注意默认是Listen:80 如果默认被其他程序占用最好修改一个端口将d......
  • PHP开发:代码风格、重构和设计模式的实践
    一、代码风格和规范:采用一致的代码风格和规范有助于提高代码的可读性和可维护性。我们将介绍一些常见的PHP代码风格指南,如PSR-12(PHPStandardRecommendation),以及一些静态代码分析工具,如PHPCodeSniffer,可以帮助您自动检测代码规范问题。示例代码风格(使用PSR-12):<?phpnamespaceV......
  • PHP开发:版本管理、服务器配置和最佳实践
    一、PHP版本和扩展管理:在PHP开发中,使用最新版本的PHP和相关扩展非常重要。版本更新通常包含新功能、修复漏洞和提高性能。我们将介绍如何使用包管理器(如Composer)来管理PHP的版本和扩展,并演示如何安装和更新它们。示例代码:#使用Composer安装PHP依赖包composerrequirevendor/pac......
  • PHPSTORM 2020中文版下载 软件大全
    PhpStorm和ZendStudio一样,依然是Java内核开发的一款功能强大的PHPIDE代码编辑器,支持windows和linux平台。PhpStorm7开始支持PHP5.5了,改进PHP代码高亮颜色等。PhpStorm常适合于PHP开发人员及前端工程师。提供诸于:智能HTML/CSS/JavaScript/PHP编辑、代码质量分析、版本控制集成(SVN......
  • 80端口被占用怎么办(以phpstudy为例)
    netstat-anonetshhttpshowservicestate这里主要看 进程ID,根据ID去任务管理器中找对应的PID进程,该结束的结束,该停的停 ......
  • php交换两个变量的值,不使用第三个变量
    参考https://www.php.net/manual/zh/function.list.php代码#第一种PHP4,PHP5,PHP7,PHP8#像array()一样,这不是真正的函数,而是语言结构。list()可以在单次操作内为一组变量赋值。字符串不能解包且list()表达式不能完全为空。list($a,$b)=[$b,$a];#PHP......
  • k8sphp业务
    1.K8S部署初始化准备1.1系统安装地址规划,根据实际情况进行修改主机名IP操作系统master10.0.0.10ubuntu22.04worker0110.0.0.11ubuntu22.04worker0210.0.0.12ubuntu22.04下载地址:https://mirrors.aliyun.com/ubuntu-releases/bionic/ubuntu-18.04......