Skip to content

Instantly share code, notes, and snippets.

@iammuttaqi
Created February 2, 2025 17:53
Show Gist options
  • Select an option

  • Save iammuttaqi/98debab0d6fa2e462ce7bc2156fc9c5e to your computer and use it in GitHub Desktop.

Select an option

Save iammuttaqi/98debab0d6fa2e462ce7bc2156fc9c5e to your computer and use it in GitHub Desktop.
Image Optimizer for filamentphp FileUpload input. using intervention/image-laravel package
<?php
namespace App\Helpers;
use Filament\Forms\Components\FileUpload;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Str;
use Livewire\Features\SupportFileUploads\TemporaryUploadedFile;
class ImageOptimizer
{
/**
* Create a new class instance.
*/
public function __construct()
{
//
}
public static function optimize(?int $width = null, ?int $height = null, int $quality = 100): callable
{
return function (FileUpload $component, TemporaryUploadedFile $file) use ($width, $height, $quality) {
$filename = Str::replace($file->getClientOriginalExtension(), 'webp', $component->getUploadedFileNameForStorage($file));
$file_path = $component->getDirectory() . '/' . $filename;
$compressed_image = \Intervention\Image\Laravel\Facades\Image::read($file->getRealPath())->resize(width: $width, height: $height)->toWebp($quality);
Storage::disk($component->getDiskName())->put($file_path, $compressed_image);
return $file_path;
};
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment