When I upload images to Dropzone.js they keep their aspect ratio and just get cropped. They look like this which is good:
When I use this code to display previously uploaded files:
...
$.getJSON('files/list-all', function(data) {
$.each(data, function(index, val) {
var mockFile = { name: val.name, size: val.size };
thisDropZone.options.addedfile.call(thisDropZone, mockFile);
thisDropZone.options.thumbnail.call(thisDropZone, mockFile, "uploads/" + val.id + "." + val.extension);
});
});
...
I get these squished versions of the images:
So the question is how do I get the thumbnails to look good like they when you upload?
Same problem, my workaround. It's not the cropped effect, but keeps the aspect ratio. It also centers the picture within the frame.
It goes by implementing the 'fileadded' listener in the 'init' option on dropzone creation. Then, adjust the image.
Steps:
Listing:
var thisDropZone = new Dropzone($("#thisDropZone"), {
url: "files/upload",
init: function () {
this.on("addedfile", function (file) {
var img = $(file.previewTemplate).find("img");
img[0].onload = function () {
var max = this.width > this.height ? this.width : this.height;
var ratio = 100.0 / max;
var width = this.width * ratio;
var height = this.height * ratio;
img.css({
width: width + "px",
height: height + "px",
top: ((100 - height) / 2) + "px",
left: ((100 - width) / 2) + "px"
});
};
}
}
});
The recurring magic number '100' is the 'width' and 'weight' property values for IMG element, as defined by the css class '.dropzone' in theirs default stylesheet 'dropzone.css'.
To achieve this, you can't call the 'addedfile' event like you do; you have to trigger it like this:
$.getJSON('files/list-all', function(data) {
$.each(data, function(index, val) {
var mockFile = { name: val.name, size: val.size };
thisDropZone.emit("addedfile", mockFile);
thisDropZone.emit("thumbnail", mockFile, "uploads/" + val.id + "." + val.extension);
});
});
Hope it helps!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With