Danish
Danish

Reputation: 353

How to encode jpeg/jpg to webp in laravel

I'm working with laravel 7 and using intervention/image to store images. However, I want to encode and store images as webp, I'm using the following code but it is not encoding the image in webp rather it is storing in the original format. Can you please tell me what I'm doing wrong?

public function storePoster(Request $request, Tournament $tournament)
{
    if ($request->hasFile('poster')) {
        $tournament->update([
            'poster' => $request->poster->store('images', ['disk' => 'public_uploads']),
        ]);
        $image = Image::make(public_path('uploads/' . $tournament->poster))->encode('webp', 90)->resize(200, 250);
        $image->save();
    }
}

Upvotes: 7

Views: 30477

Answers (3)

M Sohaib
M Sohaib

Reputation: 21

if you want to convert image in to WEBP without any service or package, try this method. work for me. have any question can ask. Thankyou

        $post = $request->all();
        $file = @$post['file'];
        $code = 200;
        $extension = $file->getClientOriginalExtension();
        $imageName = $file->getClientOriginalName();
        $path = 'your_path';

        if(in_array($extension,["jpeg","jpg","png"])){
    //old image
            $webp = public_path().'/'.$path.'/'.$imageName;
            $im = imagecreatefromstring(file_get_contents($webp));
            imagepalettetotruecolor($im);
    // have exact value with WEBP extension
            $new_webp = preg_replace('"\.(jpg|jpeg|png|webp)$"', '.webp', $webp);
    //del old image
            unlink($webp);
    // set qualityy according to requirement
            return imagewebp($im, $new_webp, 50);
            
        }

Upvotes: 0

Gim
Gim

Reputation: 89

This is my code to convert to .webp and resize (keep image's ratio)

$imageResize = Image::make($image)->encode('webp', 90);
if ($imageResize->width() > 380){
    $imageResize->resize(380, null, function ($constraint) {
        $constraint->aspectRatio();
    });
}
$destinationPath = public_path('/imgs/covers/');
$imageResize->save($destinationPath.$name);

Upvotes: 0

STA
STA

Reputation: 34728

Try this :

public function storePoster(Request $request, Tournament $tournament)
{
    if ($request->hasFile('poster')) {
        $tournament->update([
            'poster' => $request->poster->store('images', ['disk' => 'public_uploads']),
        ]);

       $classifiedImg = $request->file('poster');
       $filename = $classifiedImg->getClientOriginalExtension();
       // Intervention 
       $image = Image::make($classifiedImg)->encode('webp', 90)->resize(200, 250)->save(public_path('uploads/'  .  $filename . '.webp')
    }
}

Upvotes: 15

Related Questions