Welcome Guest, Not a member yet? Register   Sign In
JPG or PNG to WebP converter simple class

(This post was last modified: 05-22-2024, 12:03 AM by rmcdahal. Edit Reason: Wired fonts class )

Encountered an issue with converting JPG or PNG images to WebP format during upload. I tried using the Intervention Image library and other libraries but got stuck. Below is a simple CodeIgniter 4 library class that converts a JPG or PNG image to WebP during upload and deletes the original uploaded file. Here is the code:

PHP Code:
namespace Travo\Admin\Libraries;

    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->fullPathPATHINFO_EXTENSION);
        $this->newFileFullPath str_replace('.' $this->extension'.webp'$this->fullPath);

        $sourceImage $this->createImageFromPath($this->fullPath);

        if ($sourceImage) {

            if ($this->deleteOriginal) {

            $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);
                return false;

    private function convertToWebp($sourceImage)

To init , $webp = new ToWebp(); 
$result = $webp->convert($orginal_file_path, 70, false);
I have implemented this in my Codeigniter Blog 

Thanks for Sharing.
What did you Try? What did you Get? What did you Expect?

Joined CodeIgniter Community 2009.  ( Skype: insitfx )

(This post was last modified: 05-22-2024, 06:52 AM by luckmoshy.)

another simple  approach

PHP Code:
if ($image->isValid() && !$image->hasMoved()) { 
  $newBanner =str_ireplace(['.jpeg','.jpg','.png'],'.webp',$image->getRandomName());

          $save =[
'image'=>$newBanner ?? "imageplaceholder.png",
Codeigniter First, Codeigniter Then You!!


Thank you for sharing

Theme © iAndrew 2016 - Forum software by © MyBB