Skip to content

Instantly share code, notes, and snippets.

@stonehippo
Created August 17, 2015 15:56
Show Gist options
  • Save stonehippo/02f33ace7c40cff566fd to your computer and use it in GitHub Desktop.
Save stonehippo/02f33ace7c40cff566fd to your computer and use it in GitHub Desktop.
A snippet to scale down an image in-browser
/*
Takes a file object, assumed to be an image, and scales it to fit within
a maximum width and height.
Returns the resulting scaled image as a dataURL.
*/
function imageDownScaler(file, callback, maxWidth, maxHeight) {
var scaleDimensionsIfNeeded = function(w, h, maxW, maxH) {
if (w > maxW || h > maxH) {
if (w > h) {
return {width: maxW, height: h * maxW / w};
} else {
return {width: w * maxH / h, height: maxH};
}
}
return {width: w, height: h};
}
var reader = new FileReader();
reader.onload = function() {
var image = new Image();
image.src = reader.result;
image.onload = function() {
var scale = scaleDimensionsIfNeeded(image.width, image.height, maxWidth | 320, maxHeight || 320);
var canvas = document.createElement("canvas");
canvas.width = scale.width;
canvas.height =scale.height;
var ctx = canvas.getContext("2d");
ctx.drawImage(this, 0, 0, scale.width, scale.height);
callback(canvas.toDataURL());
}
}
reader.readAsDataURL(file);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment