2

My code is cropping a image but does not check if image size is larger than 15 MB. I'm using the Cropit jQuery plugin.

I am using this code to initialize the library:

(function() {
    var b;
    b = function(a) {
        return 1 === a.code ? (this.find(".error-msg").text("Please use an image that's at least " + this.outerWidth() + "px "+ this +"in width and " + this.outerHeight() + "px in height."),
                this.addClass("has-error"),
                window.setTimeout(function(a) {
                    return function() {
                        console.log(img);
                        return a.removeClass("has-error")
                    }
                }
                (this), 3e3)) : void 0
    }
    ,
    function() {
        var f;
        return f = jQuery(".image-editor"),
                f.cropit({
                    imageBackgroundBorderWidth: 70,
                    imageBackground: true,
                    imageState: {
                        src: '<%= @image.blank? ? '/assets/image_upload/image-person.png' : @image.image.url(:original) %>'
                    },
                    onImageError: b.bind(f.find(".cropit-image-preview")),
                })
    }
    ()
}
).call(this);

How can I check if image is larger than 15 MB? I tried:

    limitsize = 15;

    jQuery('.cropit-image-input').bind('change', function() {

        image = this.files[0];

        if((image.size / (1024*1024)) > limitsize) {
            jQuery('.image-editor').find(".error-msg").text("Please use an image smaller than 10 MB");
            jQuery('.image-editor').cropit('imageSrc', '<%= @image.blank? ? '/assets/image_upload/image-person.png' : @image.image.url(:original) %>');
            jQuery('.image-editor').addClass("has-error");
            window.setTimeout(function () {
                jQuery('.image-editor').removeClass("has-error")

            }, 3e3);

        }
    });

but the problem is that the library still load the > 15 image.

JSFiddle.

Michał Perłakowski
  • 88,409
  • 26
  • 156
  • 177

1 Answers1

1

You should change file input while initializing cropit to some dummy input and manually update image URL when input value changes.

Updated fiddle.

Take a look especially at these lines:

f.cropit({
  // [...]
  onImageError: b.bind(f.find(".cropit-image-preview")),
  $fileInput: jQuery("dummy-file-input")
})

// [...]

if((image.size / (1024*1024)) > limitsize) {
  // [...]
} else {
  jQuery(".image-editor").cropit("imageSrc", URL.createObjectURL(image));
}

If you want to have the image in base64, use FileReader:

var reader = new FileReader();
reader.readAsDataURL(image);
reader.addEventListener("loadend", function() {
  jQuery(".image-editor").cropit("imageSrc", reader.result);
});

Fiddle with base64.

See also: Convert blob to base64

Community
  • 1
  • 1
Michał Perłakowski
  • 88,409
  • 26
  • 156
  • 177