-
Notifications
You must be signed in to change notification settings - Fork 0
/
WebpConverter.php
50 lines (44 loc) · 1.5 KB
/
WebpConverter.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
<?php
namespace Sujan\LaravelWebpConverter;
class WebpConverter
{
/**
* Convert jpg,jpeg,png,webp image to webp,Compress & Resize Image.
*
* @return webpImage
* @throws \Exception
*/
public function webpImage($file, $filename, $location, $width = null, $height = null, $quality = null)
{
$quality = empty($quality) ? config('laravel-webp-converter.quality') : $quality;
//Supported File / Image Extensions
$extension = ['jpeg', 'jpg', 'webp', 'png'];
$ext = strtolower($file->getClientOriginalExtension());
//Check Supported File / Image Extensions
if (!in_array($ext, $extension)) {
throw new \Exception('Image format must be jpeg,jpg,png,webp');
}
// Create a new image from file
switch ($ext) {
case 'jpeg':
$image = imagecreatefromjpeg($file);
break;
case 'jpg':
$image = imagecreatefromjpeg($file);
break;
case 'png':
$image = imagecreatefrompng($file);
break;
default:
$image = imagecreatefromwebp($file);
}
if (!empty($width && $height)) {
$image = imagescale($image, $width, $height);
}
$webpImage = imagewebp($image, $location . $filename . '.' . 'webp', $quality);
if ($webpImage) {
return $webpImage;
}
throw new \Exception('Some Error Occurs');
}
}