/
OptImage.php
executable file
·85 lines (71 loc) · 2.82 KB
/
OptImage.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
81
82
83
84
85
<?php
/**
* Created by Vitaly Iegorov <egorov@samsonos.com>
* on 21.05.14 at 10:51
*/
/**
* Class for interacting with SamsonPHP
* @author Vitaly Egorov <egorov@samsonos.com>
* @copyright 2014 SamsonOS
* @version 1.0.0
*/
class OptImage extends \samson\core\ExternalModule
{
public $supported = array('jpeg', 'jpg', 'png');
/**
* Prepare collection of web-application images grouped by image type
*
* @param array $supported Collection of supported images extensions
* @return array Collection of web-application images grouped by image type
*/
protected function getImagesList(array $supported)
{
$result = array();
// Initialize array of extensions as keys
foreach($supported as $extension) {
$result[$extension] = array();
}
// Iterate gathered namespaces for their resources
foreach ($this->system->module_stack as $id => &$module) {
// Iterate supported images types
foreach ($supported as $extension) {
// If necessary resources has been collected
if (isset($module->resourceMap->$extension)) {
// Iterate resources and gather images
foreach ($module->resourceMap->$extension as & $resource) {
$result[$extension][] = $resource;
}
}
}
}
// Remove empty keys
return array_filter($result);
}
/** Module initialization */
public function init(array $params = array())
{
// TODO: Add control over tools installation
// TODO: Add control over tool output/returnval to signal error
// Get web-application supported images
foreach ($this->getImagesList($this->supported) as $extension => $images) {
// Iterate all images with this extension
foreach ($images as $image) {
// Generate hash string describing
$cacheFile = md5($image).'.'.$extension;
// Check if cache file has to be updated
if ($this->cache_refresh($cacheFile, false)) {
elapsed('Lossless compressing image: '.$image);
// Dependently on image extension use specific tool for compression
switch ($extension) {
case 'jpg':
case 'jpeg': exec('jpegoptim '.$image); break;
case 'png': exec('optipng -o7 '.$image); break;
default: elapsed('Image:'.$image.' cannot be compressed, extension not supported');
}
// Store cached empty image version to avoid duplicate compressing
file_put_contents($cacheFile, '' );
}
}
}
}
}