yano3nora
7/1/2017 - 4:50 AM

[php: imgCompress()] Attention on old code. #php

[php: imgCompress()] Attention on old code. #php

<?php
// 1. ある特定のディレクトリを参照し、中にいくつディレクトリがあるか数える
// 2. ディレクトリがあるだけ中の画像ファイル(jpg)を参照して、ファイルサイズが $size を超えるようなら圧縮処理をかける
set_time_limit(0);

// メイン関数
function imgCompress($src,$size,$comp) {
    $fs = @filesize($src);
    $jpg = @imagecreatefromjpeg($src);
    while($fs > $size && $comp > 0) {
        @imagejpeg($jpg, $src, $comp);
        $fs = filesize($src);
        @clearstatcache();
        $comp = $comp-5;
    }//while
    @imagedestroy($jpg);
}

    $size = 90000;
    $comp = 90;
    $count = 0;
    $dir_count = 0;
    $compressed = [];
    $path = "./img/profile";
    $files = scandir($path);
    foreach ($files as $value) {
        if(is_dir($path."/".$value)){
            $res_dir = opendir($path."/".$value);
            while($file_name = readdir($res_dir)){
                if (preg_match("/.+\.jpg$/i", $file_name) && filesize($path."/".$value."/".$file_name) > $size) {
                    compression($path."/".$value."/".$file_name,$size,$comp);
                    $count++;
                    array_push($compressed,$path."/".$value."/".$file_name);
                }
            }
            closedir($res_dir);
            $res_dir = null;
            $dir_count++;
        }//if
    }//foreach
    echo $dir_count." 個のディレクトリを検出し<br>";
    echo "<br>";
    echo $count." 個のファイルに対して圧縮をかけました!!<br>";
    echo "<br>";
    foreach ($compressed as $key => $value) {
        echo $key." : ".$value."<br>";
    }