分享片段用Intervention\Image处理图片,批量循环改变成webp格式。

wangsq
<?php

// include composer autoload
require 'vendor/autoload.php';

use Intervention\Image\ImageManager;

$manager = new ImageManager();
/**
 * 根据指定的目录循环遍历里面的图片文件转换成webp格式并删除原始文件
 * @param $path
 * @param $manager
 * @return void
 * @throws Exception
 * */

function convertToWebP($path, $manager)
{
    try {
        $files = scandir($path . '/');
        foreach ($files as $file) {
            if ($file === '.' || $file === '..') {
                continue;
            }
            $filePath = $path . '/' . $file;
            if (is_file($filePath)) {
                $extension = strtolower(pathinfo($filePath, PATHINFO_EXTENSION));
                if (in_array($extension, ['jpg', 'jpeg', 'png'])) {
                    $webpPath = $path . '/' . pathinfo($filePath, PATHINFO_FILENAME) . '.webp';
                    $manager->make($filePath)->encode('webp')->save($webpPath);
                    if (unlink($filePath)) {
                        echo "已删除文件" . $filePath . "\n";
                    } else {
                        echo $filePath . "文件删除失败\n";
                    }
                    echo $webpPath . "\n";
                }
            } elseif (is_dir($filePath)) {
                convertToWebP($filePath, $manager);
            }
        }
    } catch (Exception $e) {
        echo $e->getMessage();
    }
}

$dir = 'd:/web/img';
convertToWebP($dir, $manager);
427 1 0
1个评论

liziyu

大佬辛苦了,请问为什么要改为webp格式呢,使用场景怎样的呀?

  • wangsq 2023-09-20

    即使相同分辨率下,主要是压缩了图片大小^_^省流量,加快页面加载速度。当然也可以用Intervention\Image来改变图片大小。功能很多,可以参展官方看下

wangsq

470
积分
0
获赞数
0
粉丝数
2023-03-18 加入
🔝