Created
March 25, 2023 13:04
-
-
Save alalfakawma/5e2c5e8d115c552ba7d321d6610611e5 to your computer and use it in GitHub Desktop.
Convert image to webp for storage [Laravel]
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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