Created
January 11, 2017 07:30
-
-
Save mannuelf/8d30b33127873340b41ca0670b53ca5f to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
dropzone.on("addedfile", function(origFile) { | |
var MAX_WIDTH = 800; | |
var MAX_HEIGHT = 600; | |
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) { | |
dropzone.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 = dropzone.files.indexOf(origFile); | |
dropzone.files[origFileIndex] = resizedFile; | |
// Enqueue added file manually making it available for | |
// further processing by dropzone | |
dropzone.enqueueFile(resizedFile); | |
}); | |
}); | |
reader.readAsDataURL(origFile); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment