Skip to content

Instantly share code, notes, and snippets.

@jacobtwlee
Last active October 15, 2018 08:42
Show Gist options
  • Save jacobtwlee/b9acb89d9a8ebc75f669 to your computer and use it in GitHub Desktop.
Save jacobtwlee/b9acb89d9a8ebc75f669 to your computer and use it in GitHub Desktop.
Processing the image with canvas
function processFile(dataURL, fileType) {
var maxWidth = 800;
var maxHeight = 800;
var image = new Image();
image.src = dataURL;
image.onload = function () {
var width = image.width;
var height = image.height;
var shouldResize = (width > maxWidth) || (height > maxHeight);
if (!shouldResize) {
sendFile(dataURL);
return;
}
var newWidth;
var newHeight;
if (width > height) {
newHeight = height * (maxWidth / width);
newWidth = maxWidth;
} else {
newWidth = width * (maxHeight / height);
newHeight = maxHeight;
}
var canvas = document.createElement('canvas');
canvas.width = newWidth;
canvas.height = newHeight;
var context = canvas.getContext('2d');
context.drawImage(this, 0, 0, newWidth, newHeight);
dataURL = canvas.toDataURL(fileType);
sendFile(dataURL);
};
image.onerror = function () {
alert('There was an error processing your file!');
};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment