Croppr.js icon indicating copy to clipboard operation
Croppr.js copied to clipboard

How to upload cropped image?

Open idvipul opened this issue 5 years ago • 4 comments

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?

idvipul avatar Mar 15 '19 03:03 idvipul

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...

MichielioZ avatar Mar 27 '19 19:03 MichielioZ

https://www.php.net/manual/fr/function.imagecrop.php

Airone2000 avatar Nov 23 '19 21:11 Airone2000

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.

ryanb avatar Jun 04 '21 19:06 ryanb

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);

ghost avatar Aug 03 '21 14:08 ghost