If you've ever used the TinyMCE Editor with the mohamedsabil83/filament-forms-tinyeditor
package in FilamentPHP, you may have encountered warnings from Google PageSpeed about image optimization.
You can address this issue by manually converting images to WebP before uploading them, or you can automate the process using a simple trick.
In this example, we'll use Imagick, but you can also achieve this with GD.
use Mohamedsabil83\FilamentFormsTinyeditor\Components\TinyEditor;
use Livewire\Features\SupportFileUploads\TemporaryUploadedFile;
use Imagick;
TinyEditor::make('body')
->saveUploadedFileAttachmentsUsing(function (TemporaryUploadedFile $file) {
$isImage = in_array($file->getMimeType(), ['image/jpeg', 'image/png', 'image/gif']);
if(extension_loaded('imagick') && $isImage) {
$imagick = new Imagick($file->getRealPath());
$imagick->setImageFormat('webp');
$filename = Str::random(64) . '.webp';
$storePath = storage_path('app/public') . '/' . $filename;
$imagick->writeImage($storePath);
return Storage::url("/{$filename}.webp");
}
return $file->store('', 'public');
})
It will skip if the file is not an image or already in WebP format. You can customize the $storePath
variable depending on your requirements.