This repository has been archived by the owner on Aug 22, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
optimize-images.php
executable file
·58 lines (51 loc) · 1.82 KB
/
optimize-images.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
#!/usr/bin/php
<?php
require 'vendor/autoload.php';
function optimizeImage($filepath)
{
$factory = new \ImageOptimizer\OptimizerFactory();
$optimizer = $factory->get();
$optimizer->optimize($filepath);
}
function recurseImages($dir, &$initialBytes, &$bytesSaved)
{
$images = $initialBytes = $bytesSaved = 0;
$stack[] = $dir;
while ($stack) {
sort($stack);
$thisdir = array_pop($stack);
if ($dircont = scandir($thisdir)) {
for ($i = 0; isset($dircont[$i]); $i++) {
if ($dircont[$i]{0} !== '.') {
$current_file = $thisdir .'/'. $dircont[$i];
if (!is_link($current_file)) {
if (is_dir($current_file)) {
$stack[] = $current_file;
} else {
switch (strtoupper(pathinfo($current_file, PATHINFO_EXTENSION))) {
case 'GIF':
case 'PNG':
case 'JPG':
case 'JPEG':
$initialBytes += filesize($current_file);
optimizeImage($current_file);
$bytesSaved += filesize($current_file);
$images++;
break;
}
}
}
}
}
}
}
return $images;
}
if (is_dir($argv[1])) {
$time = time();
$initialBytes = $bytesSaved = 0;
$path = realpath($argv[1]);
$images = recurseImages($path, $initialBytes, $bytesSaved);
$time = time() - $time;
echo "Time: {$time}s\tImages: $images\tInitial bytes: $initialBytes\tBytes saved: $bytesSaved (". round($bytesSaved / $initialBytes * 100, 1) ."%)\n";
}