jamesssooi / Croppr.js

A vanilla JavaScript image cropper that's lightweight, awesome, and has absolutely zero dependencies.
https://jamesooi.design/Croppr.js
MIT License
396 stars 91 forks source link

How to upload cropped image? #32

Open idvipul opened 5 years ago

idvipul commented 5 years ago

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 commented 5 years ago

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 commented 4 years ago

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

ryanb commented 3 years ago

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 commented 3 years ago

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