Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

How to upload cropped image? #32

Open
idvipul opened this issue Mar 15, 2019 · 4 comments
Open

How to upload cropped image? #32

idvipul opened this issue Mar 15, 2019 · 4 comments

Comments

@idvipul
Copy link

idvipul commented Mar 15, 2019

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?

@MichielioZ
Copy link

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

@Airone2000
Copy link

@ryanb
Copy link

ryanb commented Jun 4, 2021

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.

@ghost
Copy link

ghost commented Aug 3, 2021

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

4 participants