织梦号织梦号

何其有幸,我们相遇。

基于TP5的PHP批量压缩图片

在command下创建CompressImg.php文件!

setName('compress_img')->setDescription('压缩图片');
}

protectedfunctionexecute(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);
}

protectedfunctiontask($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);
}
}
}
}}

切换到项目根目录,执行!

phpthinkcompress_img



转载保留:织梦号 » 基于TP5的PHP批量压缩图片

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

微信扫一扫打赏