Skip to content

Instantly share code, notes, and snippets.

@inca
Last active August 29, 2015 14:15
Show Gist options
  • Save inca/774763d64ff0797541e2 to your computer and use it in GitHub Desktop.
Save inca/774763d64ff0797541e2 to your computer and use it in GitHub Desktop.
Canvas-based image resize
var ImageResize = module.exports = exports = function(file) {
this.originalFile = file;
this.backgroundColor = '#fff';
};
ImageResize.prototype.resize = function(width, height, mime, cb) {
mime = mime || 'image/jpeg';
var self = this;
var reader = new FileReader();
reader.onload = onLoadFile;
reader.readAsDataURL(self.originalFile);
function onLoadFile(event) {
var img = new Image();
img.onload = onLoadImage;
img.src = event.target.result;
}
function onLoadImage() {
var dim = ImageResize.getDimensions(this.width, this.height, width, height);
var canvas = document.createElement('canvas');
canvas.width = dim.width;
canvas.height = dim.height;
canvas.style.visibility = 'hidden';
document.body.appendChild(canvas);
var ctx = canvas.getContext('2d');
if (mime == 'image/jpeg') {
ctx.fillStyle = self.backgroundColor;
ctx.fillRect(0, 0, dim.width, dim.height);
}
ctx.drawImage(this, 0, 0, dim.width, dim.height);
var dataUrl = canvas.toDataURL(mime);
var blob = ImageResize.getBlob(dataUrl);
document.body.removeChild(canvas);
cb({
dataUrl: dataUrl,
blob: blob
});
}
};
// Statics
ImageResize.getDimensions =
function(originalWidth, originalHeight, targetWidth, targetHeight) {
var w = Math.min(targetWidth, originalWidth);
var h = originalHeight / originalWidth * w;
h = Math.min(targetHeight, h);
w = originalWidth / originalHeight * h;
return {
width: w,
height: h
};
};
ImageResize.getBlob = function(dataURL) {
var BASE64_MARKER = ';base64,';
var parts = dataURL.split(BASE64_MARKER);
var contentType = parts[0].split(':')[1];
var raw = window.atob(parts[1]);
var rawLength = raw.length;
var uInt8Array = new Uint8Array(rawLength);
for (var i = 0; i < rawLength; ++i)
uInt8Array[i] = raw.charCodeAt(i);
return new Blob([uInt8Array], { type: contentType });
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment