Completed
Push — master ( 53780e...168ede )
by Emmanuel
02:11
created

GlLazyLoadImg::getMinGifDataURI()   B

Complexity

Conditions 1
Paths 1

Size

Total Lines 26
Code Lines 17

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 26
rs 8.8571
c 0
b 0
f 0
cc 1
eloc 17
nc 1
nop 5
1
<?php
2
3
/**
4
 * Lazy loading images
5
 *
6
 * PHP version 5.4
7
 *
8
 * @category  GLICER
9
 * @package   Contact
10
 * @author    Emmanuel ROECKER <[email protected]>
11
 * @author    Rym BOUCHAGOUR <[email protected]>
12
 * @copyright 2012-2013 GLICER
13
 * @license   Proprietary property of GLICER
14
 * @link      http://www.glicer.com
15
 *
16
 * Created : 8/26/16
17
 * File : GlLazyLoadImg.php
18
 *
19
 */
20
21
namespace GlLazyLoadImg;
22
23
use GlHtml\GlHtml;
24
25
class GlLazyLoadImg
26
{
27
    const BLANK = 0;
28
    const LOSSY = 1;
29
30
    /**
31
     * @var string rootpath
32
     */
33
    private $rootpath;
34
35
    /**
36
     * @var string
37
     */
38
    private $datauri;
0 ignored issues
show
Unused Code introduced by
The property $datauri is not used and could be removed.

This check marks private properties in classes that are never used. Those properties can be removed.

Loading history...
39
40
41
    /**
42
     * @var string
43
     */
44
    private $moveToAttribute;
45
46
    /**
47
     * @var array
48
     */
49
    private $excludeAttributesList;
50
51
    /**
52
     * constructor - set root directory to relative url
53
     *
54
     * @param string $rootpath
55
     * @param int    $type
56
     * @param string $moveToAttribute
57
     * @param array  $excludeAttributesList
58
     */
59
    public function __construct(
60
        $rootpath,
61
        $type = self::BLANK,
62
        $moveToAttribute = 'data-original',
63
        array $excludeAttributesList = []
64
    ) {
65
        $this->rootpath              = $rootpath;
66
        $this->type                  = $type;
0 ignored issues
show
Bug introduced by
The property type does not exist. Did you maybe forget to declare it?

In PHP it is possible to write to properties without declaring them. For example, the following is perfectly valid PHP code:

class MyClass { }

$x = new MyClass();
$x->foo = true;

Generally, it is a good practice to explictly declare properties to avoid accidental typos and provide IDE auto-completion:

class MyClass {
    public $foo;
}

$x = new MyClass();
$x->foo = true;
Loading history...
67
        $this->moveToAttribute       = $moveToAttribute;
68
        $this->excludeAttributesList = $excludeAttributesList;
69
    }
70
71
    
72
    private function gcd($a,$b) {
73
         return ($a % $b) ? $this->gcd($b,$a % $b) : $b;
74
    }
75
    
76
    /**
77
     * create lossy gif image and encode to data uri format
78
     * minimal size is jpeg
79
     *
80
     * @param     $src          resource GD library
81
     * @param int $minwidth     min width in pixels (height autocalculte)
82
     *
83
     * @return string           data uri format
84
     */
85
    public function getLossyGifDataURI($src, $minwidth = 75)
86
    {
87
        $src = imagescale($src, $minwidth, -1, IMG_NEAREST_NEIGHBOUR);
88
89
        ob_start();
90
        imagegif($src);
91
        $data = ob_get_contents();
92
        ob_end_clean();
93
94
        imagedestroy($src);
95
96
        $base64 = base64_encode($data);
97
98
        $mime = 'image/gif';
99
100
        return ('data:' . $mime . ';base64,' . $base64);
101
    }
102
103
    /**
104
     * create blank image with same size in data uri format
105
     * minimal size is gif
106
     *
107
     * @param int $red   red component background color (default 255)
108
     * @param int $green green component background color (default 255)
109
     * @param int $blue  blue component background color (default 255)
110
     *
111
     * @return string            data uri format
112
     */
113
    public function getMinGifDataURI($src, $red = 255, $green = 255, $blue = 255, $minsize = true)
0 ignored issues
show
Unused Code introduced by
The parameter $minsize is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
114
    {
115
        $width  = imagesx($src);
116
        $height = imagesy($src);
117
118
        $gcd    = $this->gcd($width, $height);
119
        $width  = $width / $gcd;
120
        $height = $height / $gcd;
121
            
122
        $img   = imagecreatetruecolor($width, $height);
123
        $bgcol = imagecolorallocate($img, $red, $green, $blue);
124
        imageFill($img, 0, 0, $bgcol);
125
126
        ob_start();
127
        imagegif($img);
128
        $data = ob_get_contents();
129
        ob_end_clean();
130
131
        $base64 = base64_encode($data);
132
133
        imagedestroy($img);
134
135
        $mime = 'image/gif';
136
137
        return ('data:' . $mime . ';base64,' . $base64);
138
    }
139
140
141
    /**
142
     * find type of image and open it
143
     *
144
     * @param string $file
145
     *
146
     * @return bool|resource
147
     */
148
    private function openImage($file)
149
    {
150
        if (!file_exists($file)) {
151
            return false;
152
        }
153
154
        $size = getimagesize($file);
155
        switch ($size["mime"]) {
156
            case "image/jpeg":
157
                $im = imagecreatefromjpeg($file);
158
                break;
159
            case "image/gif":
160
                $im = imagecreatefromgif($file);
161
                break;
162
            case "image/png":
163
                $im = imagecreatefrompng($file);
164
                break;
165
            default:
166
                $im = false;
167
                break;
168
        }
169
170
        return $im;
171
    }
172
173
    /**
174
     * replace all src attributes from img tags with datauri and set another attribute with old src value
175
     * support jpeg, png or gif file format
176
     *
177
     * @param string $html
178
     *
179
     * @throws \Exception
180
     * @return string
181
     */
182
    public function autoDataURI($html)
183
    {        
184
        $html = new GlHtml($html);
185
        $imgs = $html->get('img');
186
        foreach ($imgs as $img) {
187
            $src          = $img->getAttribute('src');
188
            $pathimagesrc = $this->rootpath . '/' . $src;
189
190
            $imgbin = $this->openImage($pathimagesrc);
191
            if ($imgbin) {
192
                switch ($this->type) {
193
                    case self::BLANK:
194
                        $datauri = $this->getMinGifDataURI($imgbin);
195
                        break;
196
                    case self::LOSSY:
197
                        $datauri = $this->getLossyGifDataURI($imgbin);
198
                        break;
199
                    default:
200
                        throw new \Exception("Type unknown (only self::BLANK=0 or self::LOSSY=1 accepted) : " . $this->type);
201
                }
202
203
                $width  = imagesx($imgbin);
204
                $height = imagesy($imgbin);
205
                $img->setAttributes(['width' => $width, 'height' => $height]);
206
207
                if (!$img->hasAttributes($this->excludeAttributesList)) {
208
                    $img->setAttributes([$this->moveToAttribute => $src, 'src' => $datauri]);
209
                }
210
                imagedestroy($imgbin);
211
            }
212
        }
213
214
        return $html->html();
215
    }
216
}
217