<?php
namespace Travo\Admin\Libraries;
class ToWebp
{
private $fullPath;
private $outPutQuality;
private $deleteOriginal;
private $extension;
private $newFileFullPath;
public function __construct()
{
// Initialize any necessary properties here
}
public function convert($fullPath, $outPutQuality = 100, $deleteOriginal = true)
{
$this->fullPath = $fullPath;
$this->outPutQuality = $outPutQuality;
$this->deleteOriginal = $deleteOriginal;
if (!file_exists($this->fullPath)) {
throw new \InvalidArgumentException('File does not exist');
}
$this->extension = pathinfo($this->fullPath, PATHINFO_EXTENSION);
$this->newFileFullPath = str_replace('.' . $this->extension, '.webp', $this->fullPath);
$sourceImage = $this->createImageFromPath($this->fullPath);
if ($sourceImage) {
$this->convertToWebp($sourceImage);
imagedestroy($sourceImage);
if ($this->deleteOriginal) {
unlink($this->fullPath);
}
$newPathInfo = explode('/', $this->newFileFullPath);
$finalImage = end($newPathInfo);
return (object) [
'fullPath' => $this->newFileFullPath,
'file' => $finalImage,
'status' => 1,
];
} else {
throw new \RuntimeException('Given file cannot be converted to WebP');
}
}
private function createImageFromPath($path)
{
switch (exif_imagetype($path)) {
case IMAGETYPE_PNG:
return imagecreatefrompng($path);
case IMAGETYPE_JPEG:
return imagecreatefromjpeg($path);
case IMAGETYPE_GIF:
return imagecreatefromgif($path);
default:
return false;
}
}
private function convertToWebp($sourceImage)
{
imagepalettetotruecolor($sourceImage);
imagealphablending($sourceImage, true);
imagesavealpha($sourceImage, true);
imagewebp($sourceImage, $this->newFileFullPath, $this->outPutQuality);
}
}
?>
To init , $webp = new ToWebp();
$result = $webp->convert($orginal_file_path, 70, false);
I have implemented this in my Codeigniter Blog