1+ <?php
2+
3+ class ImageHelper
4+ {
5+
6+ public function __construct ()
7+ {
8+
9+ }
10+
11+ /**
12+ * Converts .jpg, .png and .gif images into .webp format
13+ * @param string $source the source image path to convert
14+ * @param int $quality ranges from 0 (worst quality, smaller file) to 100 (best quality, biggest file).
15+ * @param bool $removeOld true if you want to delete the original file
16+ * @return string returns the .webp file path
17+ */
18+ public function ConvertImageToWebP (string $ source , int $ quality = 100 , bool $ removeOld = false ): string
19+ {
20+ $ dir = pathinfo ($ source , PATHINFO_DIRNAME );
21+ $ name = pathinfo ($ source , PATHINFO_FILENAME );
22+ $ destination = $ dir . DIRECTORY_SEPARATOR . $ name . '.webp ' ;
23+ $ info = getimagesize ($ source );
24+ $ isAlpha = false ;
25+ if ($ info ['mime ' ] == 'image/jpeg ' )
26+ {
27+ $ image = imagecreatefromjpeg ($ source );
28+ }
29+ else if ($ info ['mime ' ] == 'image/gif ' )
30+ {
31+ $ isAlpha = true ;
32+ $ image = imagecreatefromgif ($ source );
33+ }
34+ else if ($ info ['mime ' ] == 'image/png ' )
35+ {
36+ $ isAlpha = true ;
37+ $ image = imagecreatefrompng ($ source );
38+ }
39+ else
40+ {
41+ return $ source ;
42+ }
43+
44+ if ($ isAlpha )
45+ {
46+ imagepalettetotruecolor ($ image );
47+ imagealphablending ($ image , true );
48+ imagesavealpha ($ image , true );
49+ }
50+ imagewebp ($ image , $ destination , $ quality );
51+
52+ if ($ removeOld )
53+ {
54+ unlink ($ source );
55+ }
56+
57+ return $ destination ;
58+ }
59+
60+
61+ }
62+
63+ ?>
0 commit comments