0

Client-side image compression from DropZone. There are a few images that don't work with the compressor for some reason, and I can't figure out why.

<script>
var myDropzone = new Dropzone("div#dropZone",
    {
        autoQueue: false,
        autoProcessQueue: false,
        createImageThumbnails: true,
        url: '/MA/ShowPhotos/Home/UploadImage',
        dictDefaultMessage: 'Drag and Drop Files Here or Click Here to Upload ---- Cannot load more than 50 photos at a time',
        maxFiles: 50,
        init: function () {
            this.on('success', function (file) {
                if (this.getQueuedFiles().length == 0 && this.getUploadingFiles().length == 0) {
                    location.reload();
                }
            });
            this.on("error", function (file, errorMessage) {
                alert("error : " + errorMessage);
            });
            this.on("maxfilesexceeded", function (file) {
                this.removeAllFiles();
                this.addFile(file);
            });
            this.on("sending", function (file, xhr, formData) {
                formData.append('somethingNumber', $('#SomethingNumberSearched').val());

            });
        },
        success: function (file, rsp) {
            this.removeFile(file);
            $("#dropZone").css('background-color', 'inherit');
        },
        error: function (file, err, xhr) {
            if (err != undefined) {
                this.removeFile(file);
                $("#dropZone").css('background-color', 'inherit');
                if (err === "Server responded with 0 code.") {
                    alert("Error")
                }
            }
        },

        dragover: function (file) {
            $("#dropZone").css('background-color', '#9FFF80');
        },
        dragleave: function (file) {
            $("#dropZone").css('background-color', 'inherit');
        }
    });
$("#button").click(function (e) {
    alert("Uploading image");
    e.preventDefault();
    myDropzone.processQueue();
});
myDropzone.on("addedfile", function (origFile) {
    if (document.getElementById('compressCheckbox').checked == false) {
        $("#dialog-confirm").html("Do you want to compress the image?");

        // Define the Dialog and its properties.
        $("#dialog-confirm").dialog({
            resizable: false,
            modal: true,
            title: "Compress image?",
            height: 250,
            width: 400,
            buttons: {
                "Yes": function () {
                    $(this).dialog('close');
                    document.getElementById('compressCheckbox').checked = true;
                },
                "No": function () {
                    $(this).dialog('close');
                }
            }
        });
    }
    // Raised from 800 x 600
    var MAX_WIDTH = 1000;
    var MAX_HEIGHT = 800;

    var reader = new FileReader();

    // Convert file to img

    reader.addEventListener("load", function (event) {

        var origImg = new Image();
        origImg.src = event.target.result;

        origImg.addEventListener("load", function (event) {

            var width = event.target.width;
            var height = event.target.height;


            // Don't resize if it's small enough

            if (width <= MAX_WIDTH && height <= MAX_HEIGHT) {
                myDropzone.enqueueFile(origFile);
                return;
            }


            // Calc new dims otherwise

            if (width > height) {
                if (width > MAX_WIDTH) {
                    height *= MAX_WIDTH / width;
                    width = MAX_WIDTH;
                }
            } else {
                if (height > MAX_HEIGHT) {
                    width *= MAX_HEIGHT / height;
                    height = MAX_HEIGHT;
                }
            }


            // Resize

            var canvas = document.createElement('canvas');
            canvas.width = width;
            canvas.height = height;

            var ctx = canvas.getContext("2d");
            ctx.drawImage(origImg, 0, 0, width, height);

            var resizedFile = base64ToFile(canvas.toDataURL(), origFile);


            // Replace original with resized

            var origFileIndex = myDropzone.files.indexOf(origFile);
            myDropzone.files[origFileIndex] = resizedFile;


            // Enqueue added file manually making it available for
            // further processing by dropzone
            myDropzone.enqueueFile(resizedFile);
        });
    });
    reader.readAsDataURL(origFile);
});
function base64ToFile(dataURI, origFile) {
    // Checks to see if compression was checked or not
    if (document.getElementById('compressCheckbox').checked) {
        var byteString, mimestring;

        if (dataURI.split(',')[0].indexOf('base64') !== -1) {
            byteString = atob(dataURI.split(',')[1]);
        } else {
            byteString = decodeURI(dataURI.split(',')[1]);
        }

        mimestring = dataURI.split(',')[0].split(':')[1].split(';')[0];

        var content = new Array();
        for (var i = 0; i < byteString.length; i++) {
            content[i] = byteString.charCodeAt(i);
        }

        var newFile = new File(
            [new Uint8Array(content)], origFile.name, { type: mimestring }
        );


        // Copy props set by the dropzone in the original file

        var origProps = [
            "upload", "status", "previewElement", "previewTemplate", "accepted"
        ];

        $.each(origProps, function (i, p) {
            newFile[p] = origFile[p];
        });

        return newFile;
    } else { return origFile; } // User did not select to compress file
}

This script sends the image to the controller/action: '/MA/ShowPhotos/Home/UploadImage'. The controller method just uploads the image to an AWS S3 bucket. The controller works the way it's supposed to.

Thomas Stout
  • 503
  • 1
  • 4
  • 8

0 Answers0