Hongmu Notes
Home Language Notes PHP batch compression of images in the server
Language Notes PHP

PHP batch compression of images in the server

PHP batch compression of images in the server

Copy and paste this entire paragraph to execute.

cat > /www/wwwroot/blog2.1.4s5.cn/compress.php << 'EOF'
<?php
/**
 * WebP 图片批量压缩脚本
 */

// ---- 加大内存 ----
ini_set('memory_limit', '512M');
set_time_limit(0);

$dir     = '/www/wwwroot/blog2.1.4s5.cn/wp-content/uploads/titlepic';
$backup  = '/www/wwwroot/blog2.1.4s5.cn/wp-content/uploads/titlepic_bak';
$quality = 80;
$maxW    = 1000;

if (!function_exists('imagecreatefromwebp')) {
    die("❌ 当前 PHP 没有 WebP 支持\n");
}

if (!is_dir($dir)) die("❌ 目录不存在:$dir\n");

// ---- 备份 ----
if (!is_dir($backup)) {
    echo " 备份原图到 $backup ...\n";
    exec("cp -r " . escapeshellarg($dir) . " " . escapeshellarg($backup));
    echo "✅ 备份完成\n\n";
}

$files = glob($dir . '/*.webp');
$total = count($files);

echo " 开始压缩(质量 " . $quality . ",最大宽度 " . $maxW . "px),共 " . $total . " 张\n\n";

$ok = 0;
$skip = 0;
$before = 0;
$after = 0;

foreach ($files as $i => $file) {
    $size1 = filesize($file);
    $before += $size1;

    $img = @imagecreatefromwebp($file);
    if (!$img) {
        $skip++;
        $after += $size1;
        continue;
    }

    $w = imagesx($img);
    $h = imagesy($img);

    // 缩放
    if ($w > $maxW) {
        $newW = $maxW;
        $newH = (int)round($h * ($maxW / $w));
        $newImg = imagecreatetruecolor($newW, $newH);
        imagealphablending($newImg, false);
        imagesavealpha($newImg, true);
        imagecopyresampled($newImg, $img, 0, 0, 0, 0, $newW, $newH, $w, $h);
        imagedestroy($img);
        $img = $newImg;
    }

    // 保存
    $tmpFile = $file . '.tmp';
    $saved = imagewebp($img, $tmpFile, $quality);
    imagedestroy($img);

    if (!$saved || !file_exists($tmpFile)) {
        $skip++;
        $after += $size1;
        @unlink($tmpFile);
        continue;
    }

    $size2 = filesize($tmpFile);

    if ($size2 < $size1) {
        rename($tmpFile, $file);
        $ok++;
        $after += $size2;

        if ($ok % 20 === 0) {
            echo "  已压缩 " . $ok . " 张...\n";
        }
    } else {
        @unlink($tmpFile);
        $skip++;
        $after += $size1;
    }

    // 强制释放
    gc_collect_cycles();
}

echo "\n";
echo "============================================\n";
echo "✅ 处理完成\n";
echo "============================================\n";
echo "总计:    " . $total . " 张\n";
echo "已压缩:  " . $ok . " 张\n";
echo "跳过:    " . $skip . " 张\n";
echo "\n";
echo "压缩前:  " . round($before / 1024 / 1024, 1) . " MB\n";
echo "压缩后:  " . round($after / 1024 / 1024, 1) . " MB\n";

if ($before > $after) {
    $saved = $before - $after;
    $pct = round($saved * 100 / $before, 1);
    echo "节省:    " . round($saved / 1024 / 1024, 1) . " MB(约 " . $pct . "%)\n";
}

echo "\n 原图备份:" . $backup . "\n";
echo " 满意后可删:rm -rf " . $backup . "\n";
EOF

php /www/wwwroot/blog2.1.4s5.cn/compress.php

Expected Output

 开始压缩(质量 80,最大宽度 1000px),共 202 张

  已压缩 20 张...
  已压缩 40 张...
  ...

============================================
✅ 处理完成
============================================
总计:    202 张
已压缩:  202 张
跳过:    0 张

压缩前:  111 MB
压缩后:  12 MB
节省:    99 MB(约 89%)

Check individual effect

ls -lh /www/wwwroot/blog2.1.4s5.cn/wp-content/uploads/titlepic/166.webp
微信赞赏

WeChat

支付宝赞赏

Alipay

✍️ Author: Hong Mu

webmaster · Thanks for reading, stay tuned for more exciting content

Author homepage View home page →

Related articles

PHP ob function record

PHP ob function record Language Notes PHP

Usage of the following three functions ob_get_contents(); ob_end_clean(); ob_start(); You can use these functions to buffer local files and execute local script code. Use ob_start() to save the output code into the buffer, and the page will not be displayed; then use ob_get_contents to get the data in the buffer. o…
👁 140
PHP preg

PHP preg Language Notes PHP

The preg_match_all function is used to perform a global regular expression match. preg_match_all() Syntax int preg_match_all ( string $pattern , string $subject [, array &$matches [, int $flags = PREG…
👁 169
Detailed explanation of PHP ternary operator and if

Detailed explanation of PHP ternary operator and if Language Notes PHP

Ternary operator condition ? Result 1 : Result 2 Explanation: The position in front of the question mark is the condition for judgment. If the condition is met, the result is 1, and if it is not met, the result is 2. This article compares and explains the ternary operator and if...else... in detail. I hope it will be helpful to everyone. Today when I was revising my paper online, I encountered a statement that I couldn’t understand: $if_summary = $row['IF_SUMMARY']=…
👁 188
PHP cast type

PHP cast type Language Notes PHP PHP collection PHP and mysql

Get the data type 1. If you want to check the value and type of an expression, use var_dump(). 2. If you just want to get an easy-to-read type expression for debugging, use gettype(). 3. To check a certain type, do not use gettype(), but use the is_type() function. Converting Strings to Numbers When a string is evaluated as a number, the result is determined according to the following rules...
👁 232

Recommended reading

Packaging and Printing Equipment Website Template 0618

Packaging and Printing Equipment Website Template 0618 Practical Collection Yiyou template

An eyouCMS website template designed for the packaging, printing, and printing equipment industry. Its professional and practical design style is ideal for showcasing printing equipment, packaging products, and manufacturing technologies. This template helps printing and packaging enterprises demonstrate their capabilities online and attract brand customers. Template Display | Installation Instructions | Website Backend: /login.php | Username: admin | Password: admin | Related Articles: Summary of Common Installation Issues for EyouCMS | EyouCMS (Ey...
👁 38
(PC + WAP) Marketing-oriented green municipal landscaping website template (PbootCMS); Landscape architecture design website source code – 0105

(PC + WAP) Marketing-oriented green municipal landscaping website template (PbootCMS); Landscape architecture design website source code – 0105 Practical Collection pbootcms Template

This PbootCMS template is designed specifically for the marketing-oriented municipal landscaping and garden architecture design sector, supporting access via both PC and WAP devices. Its natural and sophisticated design style is ideal for showcasing landscape design projects, greening initiatives, and plant arrangements. It serves as a powerful tool for landscape architecture firms or municipal engineering companies to build their brand identity and acquire new customers. Template Display | Installation Instructions | Website Backend: /admin.php | Username: admin | Password: admin...
👁 46
php split a string into its constituent characters

php split a string into its constituent characters Language Notes PHP

Question: How to split a string into its constituent characters in PHP? For example, hello -> [h, e, l, l, o] There are three methods: This is the string that needs to be split: $str = 'Hello sample'; The length of the string: $len = mb_strlen($str, 'utf8'); // 7 The first way: $arr = str_…
👁 182
Custom Dining Table and Chair Furniture Website Template – 0878

Custom Dining Table and Chair Furniture Website Template – 0878 Practical Collection Yiyou template

An EyouCMS website template designed for the custom furniture industry – including dining tables, chairs, and other furniture products. Its modern and practical design effectively showcases dining table and chair products, customisation services, and spatial solutions. This template helps furniture brands showcase their products online and attract restaurant and corporate clients. Template Preview | Installation Instructions | Website Backend: /login.php | Username: admin | Password: admin | Related Articles: Summary of Common Installation Issues for EyouCMS | EyouCMS...
👁 40
(Adaptive mobile phone) Advertising brand planning company website pbootcms template Advertising brand planning and design company website source code download 0345

(Adaptive mobile phone) Advertising brand planning company website pbootcms template Advertising brand planning and design company website source code download 0345 Practical Collection pbootcms Template

本套自适应手机端的广告品牌策划与设计公司PbootCMS网站模板。 The design style is creative marketing, suitable for advertising companies and brand planning agencies to display cases and creative capabilities. It helps advertising companies attract brand customers online and expand business. Template display Installation instructions Website backend: /admin.php Account: admin Password: admin Unzip password: www.4s5.cn Related articles...
👁 62
Visual Brand Innovation Design Website Template 1118

Visual Brand Innovation Design Website Template 1118 Practical Collection Yiyou template

This EyouCMS template is designed for a visually-driven brand innovation website, featuring a creative and stylish design approach that effectively showcases brand design works, innovative case studies, and design concepts. It enables brand design agencies to demonstrate their professional expertise online and attract corporate clients. Template Display | Installation Instructions | Website Backend: /login.php | Username: admin | Password: admin | Related Articles: Summary of Common Installation Issues for EyouCMS | EyouCMS (...
👁 34