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

发布时间 2023-06-18 17:00:41作者: 风意不止
<?php
/**
 * Created by PhpStorm.
 * User: zhuo <779635593@qq.com>
 * 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);
                }
            }
        }
    }
}