PHP 对 PNG、JPG、JPEG、GIF、WebP 等格式图片进行压缩

2024-09-24T14:52:13+08:00 | 2 minutes read | Update at 2024-09-24T14:52:13+08:00

@ sqrtcat

原生 PHP 对 PNG、JPG、JPEG、GIF、WebP 等常用图片格式进行压缩,无第三方扩展依赖,仅需简单配置即可使用,支持 PNG 透明背景。

支持覆盖源文件或另行生成新文件(输出至与输入目录同级 ./output 文件夹下)。

将脚本保存至待处理图片目录的同级即可,并将 $input_dir 修改为待处理图片目录的路径(php image_compress.php)。

<?php

ini_set('memory_limit', '512M');

// 待处理图片目录
$input_dir = './input';

// 压缩采样率 0.7 表示压缩率为 70%
const COMPRESS_RATE = 0.7;

// 是否覆写源文件 false 的话会生成新的文件将会存储在
// $input_dir 同级的 ./output 文件夹下
const OVER_WRITE_SRC = false;

compressImg($input_dir);

/**
 * 递归遍历 folder_path 目录下的所有的图片文件并压缩
 * @param $folder_path
 */
function compressImg($folder_path)
{
    // $folder_path = realpath($folder_path);
    $handle = opendir($folder_path);
    while (false !== ($file = readdir($handle))) {
        if ($file != '.' && $file != '..') {
            $file_path = str_replace('.//', './', $folder_path.'/'.$file);
            if (is_dir($file_path)) {
                compressImg($file_path); // 递归遍历子文件夹
            } else {
                $ext = explode('/', mime_content_type($file_path))[1];
                
                echo $file_path.' - '.$ext."\n"; // 处理文件操作
                
                if (!in_array($ext, ['png', 'jpg', 'jpeg', 'gif', 'webp'])) {
                    continue;
                }
                
                list($width, $height) = getimagesize($file_path);
                if (empty($width) || empty($height)) {
                    continue;
                }
                
                switch ($ext) {
                    case 'png':
                        $img = imagecreatefrompng($file_path);
                        break;
                    case 'jpg':
                    case 'jpeg':
                        $img = imagecreatefromjpeg($file_path);
                        break;
                    case 'gif':
                        $img = imagecreatefromgif($file_path);
                        break;
                    case 'webp':
                        $img = imagecreatefromwebp($file_path);
                        break;
                }
                
                if (empty($img) || !is_resource($img)) {
                    continue;
                }
                
                $n_w = $width * COMPRESS_RATE;
                $n_h = $height * COMPRESS_RATE;
                $new = imagecreatetruecolor($n_w, $n_h);
                
                // 保持png的透明背景
                if ($ext == 'png') {
                    $transparent = imagecolorallocatealpha($new, 0, 0, 0, 127);
                    imagefill($new, 0, 0, $transparent);
                    imagealphablending($new, false);
                    imagesavealpha($new, true);
                }
                
                // imagecopyresampled($new, $img, 0, 0, 0, 0, $width, $height, $width, $height);
                imagecopyresampled($new, $img, 0, 0, 0, 0, $n_w, $n_h, $width, $height);
                //拷贝部分图像并调整
                // imagecopyresized($new, $img, 0, 0, 0, 0, $n_w, $n_h, $width, $height);
                
                if (!OVER_WRITE_SRC) {
                    $saveDir = './output/'.$folder_path;
                    if (!is_dir($saveDir)) {
                        mkdir($saveDir, 0777, true);
                    }
                    $savePath = './output/'.str_replace("./", "", $folder_path.'/'.$file);
                } else {
                    //覆盖源文件
                    $savePath = $file_path;
                }
                
                if ($ext == 'png') {
                    imagepng($new, $savePath, 9); //0-9 值越大压缩率越高
                } else {
                    imagejpeg($new, $savePath, 75); //0-100 默认 75
                }
                
                imagedestroy($new);
                imagedestroy($img);
            }
        }
    }
    closedir($handle);
}

© 2024 - 2025 sqrtcat 的博客

🌱 Powered by sqrtcat

关于我

资深云程序员,在线支持技术的讨论、攻坚、架构等高级话题,线下暂提供初级技术支持。 在线接单:App / 小程序 / WordPress / 商城 / 预约 / 企业站 / 外贸站 / MES系统 / SEO优化

wx: bigcat582

Search

如何开启检索功能,只需创建 search 文档即可。

hugo new search/_index.md