Resize Image with Dropzone.js

How to resize an Image using Dropzone.js

To resize an image using Dropzone.js, you can utilize the thumbnail event and the canvas element to perform the resizing. Here's an example of how you can achieve this:

  1. Include the Dropzone.js library in your HTML file:
<!DOCTYPE html>
<html>
<head>
  <!-- Include the necessary CSS and JavaScript files for Dropzone.js -->
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/dropzone/5.9.2/dropzone.min.css" />
  <script src="https://cdnjs.cloudflare.com/ajax/libs/dropzone/5.9.2/dropzone.min.js"></script>
</head>
<body>
  <!-- Create a Dropzone container -->
  <div id="myDropzone" class="dropzone"></div>

  <script>
    // Initialize Dropzone
    Dropzone.autoDiscover = false;
    var myDropzone = new Dropzone("#myDropzone", {
      thumbnailWidth: 200,
      thumbnailHeight: 200,
      maxFilesize: 2, // Set the maximum file size in MB
      acceptedFiles: ".jpeg,.jpg,.png" // Define the accepted file types
    });

    // Resize the image on thumbnail event
    myDropzone.on("thumbnail", function(file, dataUrl) {
      var img = new Image();
      img.onload = function() {
        // Create a canvas element
        var canvas = document.createElement("canvas");
        var ctx = canvas.getContext("2d");

        // Set the canvas dimensions to the desired size
        canvas.width = 400; // Set the width you want for the resized image
        canvas.height = 300; // Set the height you want for the resized image

        // Perform the resizing
        ctx.drawImage(img, 0, 0, canvas.width, canvas.height);

        // Get the resized image as a data URL
        var resizedDataUrl = canvas.toDataURL("image/jpeg");

        // Update the Dropzone thumbnail with the resized image
        myDropzone.emit("thumbnail", file, resizedDataUrl);
      };
      img.src = dataUrl;
    });
  </script>
</body>
</html>

In the above example, we set the thumbnailWidth and thumbnailHeight options to specify the size of the thumbnail to be displayed. The maxFilesize option limits the size of the uploaded file, and the acceptedFiles option restricts the file types to JPEG and PNG.

Inside the thumbnail event handler, we create an Image object and load the original image data URL. Then, we create a canvas element and set its dimensions to the desired size for the resized image. The drawImage method is used to perform the resizing, and the resulting image is obtained as a data URL using toDataURL. Finally, we update the Dropzone thumbnail with the resized image by emitting another thumbnail event with the resized data URL.

Please note that this example resizes the image on the client-side, and the resulting data URL will be the resized version. The original file is still uploaded, but you can access the resized image data for further processing or display purposes.