To sync the cropped image with Livewire and store it on the server, you can follow these steps:
- Initialize the Cropper.js method on the original image using Alpine.js.
- Crop the image using the Cropper.js library.
- Save the cropped image blob to a key in the Alpine component.
- Sync the cropped image to Livewire using wire:model.
- Store the cropped image on the server in the Livewire component.
Here's an updated version of the code with the necessary changes:
function data() {
return {
image: null,
image_1x1_ratio: null,
imageIsSelected: false,
imageIsCropped: false,
cropper: null,
select() {
this.image = document.getElementById('image');
if (this.cropper != null) {
this.cropper.destroy();
}
setTimeout(() => {
this.cropper = new Cropper(this.image, {
aspectRatio: 1 / 1,
zoomable: false,
crop(event) {
// Sync the cropped image to Livewire
this.image_1x1_ratio = this.cropper.getCroppedCanvas().toDataURL();
},
});
}, 500);
this.imageIsSelected = true;
},
crop() {
this.cropper.getCroppedCanvas();
this.cropper.getCroppedCanvas({
width: 160,
height: 90,
minWidth: 256,
minHeight: 256,
maxWidth: 4096,
maxHeight: 4096,
fillColor: '#fff',
imageSmoothingEnabled: false,
imageSmoothingQuality: 'high',
});
this.cropper.getCroppedCanvas().toBlob((blob) => {
this.image_1x1_ratio = URL.createObjectURL(blob);
}/*, 'image/png' */);
this.imageIsCropped = true;
}
};
}
<div x-data="data">
<input type="hidden" wire:model="croppedImage" :value="image_1x1_ratio">
<div class="w-full h-64 bg-gray-900 flex items-center justify-center">
@if($image)
<img src="{{ $image }}" id="image" class="h-full">
@else
<span class="text-white">No image selected</span>
@endif
</div>
<div class="w-full bg-gray-200 flex p-5 justify-end">
<button x-show="!imageIsSelected" type="button" class="bg-blue-500 hover:bg-blue-600 text-white px-4 py-2 rounded" @click="select">Select</button>
<button x-show="imageIsSelected" type="button" class="bg-blue-500 hover:bg-blue-600 text-white px-4 py-2 rounded" @click="crop">Crop</button>
<button x-show="imageIsCropped" type="button" class="bg-blue-500 hover:bg-blue-600 text-white px-4 py-2 rounded" wire:click="save">Save</button>
</div>
</div>
<?php
namespace App\Livewire;
use Livewire\Component;
use Livewire\WithFileUploads;
class CropImage extends Component
{
use WithFileUploads;
public $image;
public $croppedImage;
public function save()
{
// Store the cropped image on the server
$this->croppedImage->store('croppedphotos');
// Additional logic if needed
// Redirect or show success message
}
public function render()
{
return view('livewire.crop-image');
}
}
Make sure to update the Livewire component class namespace and the view file path according to your project structure.
This solution should allow you to crop the image using Cropper.js, sync the cropped image with Livewire, and store it on the server without sending the image blob in a post request.