-
Notifications
You must be signed in to change notification settings - Fork 1
/
compress-images.php
80 lines (69 loc) · 2.22 KB
/
compress-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
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
<?php
require_once('vendor/autoload.php');
$pathInput = $argv[1] ?? '/tmp/images/';
$pathOutput = $argv[2] ?? '/tmp/images/';
$tinifyAPIKey = $argv[3] ?? 'L33T-R2D2';
$imageTypes = [
image_type_to_mime_type(IMAGETYPE_PNG),
image_type_to_mime_type(IMAGETYPE_JPEG)
];
function getAllFilesAndFoldersInPath($path, $recursive = false, &$fileList = []){
$files = scandir($path);
foreach($files as $file){
$filePath = realpath($path . DIRECTORY_SEPARATOR . $file);
if(false === is_dir($filePath)) {
$fileList[] = $filePath;
} else if($file != '.' && $file != '..') {
if(true === $recursive) {
getAllFilesAndFoldersInPath($filePath, $recursive, $fileList);
}
$fileList[] = $filePath;
}
}
return $fileList;
}
function replacePathPrefixInList(array $fileList, $prefix, $replacement = '') {
foreach ($fileList as &$file) {
if(strpos($file, $prefix, 0) === 0) {
$file = preg_replace('/^' . preg_quote($prefix, '/') . '/i', $replacement, $file, 1);
}
else {
// abort - one or more of the files are NOT prefixed with the prefix-path
return false;
}
}
return $fileList;
}
// check API connection
try {
\Tinify\setKey($tinifyAPIKey);
\Tinify\validate();
} catch(\Tinify\Exception $e) {
die('Tinify API error: ' . $e->getMessage() . PHP_EOL);
}
// check directories
if(false === is_readable($pathInput) || false === is_writable($pathOutput)) {
die('Permission error - Please check given directories' . PHP_EOL);
}
// get directory content
$fileListWithAbsolutePath = getAllFilesAndFoldersInPath($pathInput, true);
$fileList = replacePathPrefixInList($fileListWithAbsolutePath, $pathInput);
if(true === empty($fileList)) {
die('Directory is empty!' . PHP_EOL);
}
// compress images
$finfo = new finfo;
foreach ($fileList as $file) {
if(in_array($finfo->file($pathInput . $file, FILEINFO_MIME_TYPE), $imageTypes)) {
try {
\Tinify\fromFile($pathInput . $file)->toFile($pathOutput. $file);
} catch(\Tinify\Exception $e) {
// catch server errors
echo 'Tinify API error: ' . $e->getMessage() . PHP_EOL;
sleep(10);
}
echo $pathInput . $file . ' → ' . $pathOutput. $file . PHP_EOL;
}
}
echo 'Done' . PHP_EOL;
echo PHP_EOL . 'API usage this month: ' . \Tinify\compressionCount() . ' compressed images' . PHP_EOL;