Spatie Laravel Media Library. How to CROP an image conversion
I am using the excellent Laravel Media Library from Spatie.
When an image is uploaded to my website it is stored using Laravel Media Library from Spatie. I have a conversion registered on the model and this works well to automatically create a cropped version of the uploaded image whilst also keeping the original image in its original state.
My question is how to allow my users to update this media conversion with their own manually applied crop. I have an edit page where the user can user cropper.js to make a crop of the image. This page then sends coordinates to the server. It sends a width, height, x and y to my image controller.
How can I update the media conversion with this new crop? Is this even the right way to use Laravel Media Library or am I fighting against the intended operation/logic behind 'Conversions'. It seems logical to me that I should be able to allow my users to control/edit image conversions whilst keeping the original image intact.
Thanks in advance to anyone that can offer advice on this.
@gtlitch
Spatie Laravel Media Library is a great package to work with Media.
Here you can try this code to achieve that functionality
// Get the media item
$media = $model->getMedia('images')->first();
// Add the crop manipulation to the image
$media->addManipulation('crop', 300, 300, 50, 50);
// Perform the image conversion
$media->performConversions();
You can also use all these methods in changing too.
// This should cause the 'main' conversion to be regenerated???
$mediaItems[0]->save();
$listing->save();
This example code causes no errors or exceptions and it successfully updates the manipulations field in the media table in the database but it doesn’t amend/alter the image conversion or responsive images? Is there a further step I am missing? Apologies for reaching out to you for help but I am getting desperate to get this working!
@gtlitch I noticed I had to add the performOnCollection method in the registerMediaConversions of the corresponding model in order to apply the custom manipulations:
public function registerMediaConversions(Media $media = null): void
{
$this->addMediaConversion('main')->...other_manipulations...->performOnCollection('gallery');
}