JeanValjean
JeanValjean

Reputation: 17713

How to create a thumbnail after cropping an image with jQuery Cropper

I'm using jQuery Cropper 3.1.3 and DropzoneJS 5.2.0, two popular JavaScript library to crop images and drop/upload images, respectively.

I will omit a lot of the code that surrounds the UI. At a certain point I select a crop area and I press a "crop" button. The button executes:

$image.cropper(
   'getCroppedCanvas', 
   {fillColor: '#fff'}
  )
  .toBlob(function (blob) {
    var croppedFile = blob; 
    croppedFile.lastModifiedDate = new Date();
    croppedFile.name = fileName;
    croppedFile.accepted = true;
    var files = myDropzone.getAcceptedFiles();
    for (var i = 0; i < files.length; i++) {
        var file = files[i];
        if (file.name === fileName) {
            myDropzone.removeFile(file);
        }
    }

    myDropzone.files.push(croppedFile);
    myDropzone.emit('addedfile', croppedFile);
    $cropperModal.modal('hide');
});

From this, I expected that the blob (file) is sent to the dropzone and added and at the end the thumbnail is created. But this does not happens. So, how can I enforce the creation of the thumbnail using DropzoneJS?

I have a complete JSFiddle here to reproduce the problem.

Upvotes: 2

Views: 2137

Answers (1)

K Scandrett
K Scandrett

Reputation: 16541

There may be a problem with the version of DropZone you're using https://gitlab.com/meno/dropzone/issues/56

You can work around it by modifying the event handler for addedfile to generate an objectURL for the preview:

myDropzone.on('addedfile', function(file) {
  if (!cropped) {
    myDropzone.removeFile(file);
    cropper(file);
  } else {
    cropped = false;
    var previewURL = URL.createObjectURL(file);
    var dzPreview = $(file.previewElement).find('img');
    dzPreview.attr("src", previewURL);
  }
});

Updated JSFiddle: https://jsfiddle.net/m02t97fa/

Upvotes: 2

Related Questions