Search code examples
imagelaravel-5gdinterventionwebp

how to convert webp image to jpeg or png by using intervention image laravel


I am developing an app in Laravel Framework (PHP). I want to upload image which have webp format and then convert it to jpeg or png image format. After converting the image i also want to upload it to s3 bucket.


Solution

  • Firstly we can use Intervention Image library. We must have php 7 and gd library installed. I am writing the commands to install gd library and webp library below (for ubuntu) :

    sudo apt-get update
    sudo apt-get install webp
    sudo apt-get install php7.0-gd (check php version and then install accordingly)
    

    now check file extension and if extension is webp, select your output file extension

    $extension = $this->file->extension();
    
    if($this->file->getMimeType() == 'image/webp'){
        $extension = 'png';
    }
    // Generate a random filename
    $fileName = time() . '_' . strtolower(uniqid()) . '.' . $extension;
    

    Now encode the image to desired format

    if($this->file->getMimeType() == 'image/webp'){
        $image = $image->encode($extension);
    }
    $image = $image->stream();
    

    Now upload the image to s3 bucket

    Storage::disk('s3')->put($folderName . '/' . $fileName, $imageNormal->__toString());