Croppr.js
Croppr.js copied to clipboard
How to upload cropped image?
I'm able to crop images on the client side using this library, but how do I upload the cropped images to the server and then display that cropped image to the client?
Croppr.js doesn't actually crop the images, it can relay the x, y, width and height of the cropped area to your server. On the server side you can then crop the uploaded images with php/node.js or whatever is suitable. Search google for how to do that in your language of choice...
https://www.php.net/manual/fr/function.imagecrop.php
Alternatively you can crop the image on the client side using a canvas. Something like this.
const sourceImage = document.getElementById("sourceImage");
const croppr = new Croppr(sourceImage, {});
// When finished cropping
const cropRect = croppr.getValue();
const canvas = document.createElement("canvas");
const context = canvas.getContext("2d");
canvas.width = cropRect.width;
canvas.height = cropRect.height;
context.drawImage(
croppr.imageEl,
cropRect.x,
cropRect.y,
cropRect.width,
cropRect.height,
0,
0,
canvas.width,
canvas.height,
);
const destinationImage = document.getElementById("destinationImage");
destinationImage.src = canvas.toDataURL();
You can do whatever you want with the data url, such as put it in a hidden field or send it to the server over an AJAX request.
Adding to the code ryanb posted (thank you very much), you can also attach the cropped image to a regular <input type="file">
and send it alongside other form data when the user clicks submit (using <form method="post" enctype="multipart/form-data">
instead of the base64 toDataURL() hidden string). Reference.
canvas.toBlob((blob) => {
var input = document.getElementById('form-input-file')
var container = new DataTransfer()
var file = new File([blob], "logo.jpg", {
type: "image/jpeg",
lastModified: new Date().getTime()
})
container.items.add(file)
input.files = container.files
console.log(input.files)
}, 'image/jpeg', 0.9);