Skip to content

Commit bca197b

Browse files
committed
ImageHelper implemented
1 parent 3d20ba3 commit bca197b

File tree

3 files changed

+65
-1
lines changed

3 files changed

+65
-1
lines changed

berry/utils.php

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,4 +2,5 @@
22

33
require_once(__DIR__ . "/utils/CrawlerDetector.php");
44
require_once(__DIR__ . "/utils/HTMLHelper.php");
5+
require_once(__DIR__ . "/utils/ImageHelper.php");
56
?>

berry/utils/ImageHelper.php

Lines changed: 63 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,63 @@
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+
?>

berry/version.php

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,6 @@
2323
SOFTWARE.
2424
*/
2525

26-
// Version 1.0.3
26+
// Version 1.0.4
2727
?>
2828

0 commit comments

Comments
 (0)