Skip to content

Instantly share code, notes, and snippets.

@alalfakawma
Created March 25, 2023 13:04
Show Gist options
  • Save alalfakawma/5e2c5e8d115c552ba7d321d6610611e5 to your computer and use it in GitHub Desktop.
Save alalfakawma/5e2c5e8d115c552ba7d321d6610611e5 to your computer and use it in GitHub Desktop.
Convert image to webp for storage [Laravel]
<?php
// NOTE: This service uses Intervention Image, which will require you
// to have Imagick or GD php extension to work
namespace App\Services;
use App\Models\Image as ImageModel;
use Illuminate\Support\Facades\File;
use Intervention\Image\Facades\Image;
class ImageConversionService
{
public static function convert(ImageModel $image, int $quality = 60): bool
{
$image = ImageModel::find($image->id);
$imagePath = storage_path('app/public/' . $image->link);
$filename = pathinfo($image->link, PATHINFO_FILENAME);
$iImage = Image::make($imagePath);
$newImageStoragePath = storage_path('app/public/media/' . $filename . '.webp');
$iImage->save($newImageStoragePath, $quality, 'webp');
$newImagePath = 'media/' . $filename . '.webp';
// NOTE: Remove the original png/jpg or whatever file
// so we can save on storage
File::delete(storage_path('app/public/') . $image->link);
$image->update([
'link' => $newImagePath,
]);
return true;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment