Skip to content

Instantly share code, notes, and snippets.

@npaton
Created June 15, 2015 14:15
Show Gist options
  • Save npaton/c3de742ffb493e8b7611 to your computer and use it in GitHub Desktop.
Save npaton/c3de742ffb493e8b7611 to your computer and use it in GitHub Desktop.
Resize image in browser (in the context of Meteor / Slingshot but applies to any in-browser resizing)
// <canvas id="resizeCanvas" width="10000" height="10000" style="display:none"></canvas>
Template.myview.events({
"change .image-select": function(e, t) {
// Verify it's an image...
console.time("total");
var img = document.createElement("img");
img.src = window.URL.createObjectURL(e.currentTarget.files[0]);
img.onload = function () {
var canvas = t.find("#resizeCanvas");
canvas.width = 10000;
canvas.height = 10000;
var ctx = canvas.getContext("2d");
var targetSize = 200;
var width = img.width;
var height = img.height;
if (width > height) {
height = targetSize;
width = Math.round(width / (img.height / targetSize));
} else {
height = Math.round(height / (img.width / targetSize) );
width = targetSize;
}
canvas.width = width;
canvas.height = height;
var ctx = canvas.getContext("2d");
ctx.drawImage(img, 0, 0, width, height);
console.log(img.width, img.height, width, height);
console.time("export");
canvas.toBlob(function(blob){
var file = new File([blob], 'pic.jpg', {
type: "image/jpeg"
// type: "image/png"
});
console.timeEnd("total");
console.timeEnd("export");
var uploader = new Slingshot.Upload("uploadAvatar");
uploader.send(file, function(err, url) {
if (err) // log error and return
// update some state
});
}, "image/jpeg", 0.9);
return;
};
}
});
if (!HTMLCanvasElement.prototype.toBlob) {
Object.defineProperty(HTMLCanvasElement.prototype, 'toBlob', {
value: function (callback, type, quality) {
var binStr = atob( this.toDataURL(type, quality).split(',')[1] ),
len = binStr.length,
arr = new Uint8Array(len);
for (var i=0; i<len; i++ ) {
arr[i] = binStr.charCodeAt(i);
}
callback( new Blob( [arr], {type: type || 'image/png'} ) );
}
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment