Created
August 17, 2015 15:56
-
-
Save stonehippo/02f33ace7c40cff566fd to your computer and use it in GitHub Desktop.
A snippet to scale down an image in-browser
This file contains hidden or 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
/* | |
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