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
原生 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);
}