Skip to content

Instantly share code, notes, and snippets.

@carlosromero
Created January 26, 2016 14:03
Show Gist options
  • Save carlosromero/da9b2fde84cc37f9e1f0 to your computer and use it in GitHub Desktop.
Save carlosromero/da9b2fde84cc37f9e1f0 to your computer and use it in GitHub Desktop.
crop and resize input file preview image
var reader = new FileReader();
reader.onload = function (e) {
// get loaded data and render thumbnail.
var imgTmp = new Image();
imgTmp.onload = function(evt) {
var tempCanvas = document.createElement("canvas"),
tCtx = tempCanvas.getContext("2d");
if (this.width > this.height) {
var width = this.height;
var imgX = (this.width - this.height)/2;
var imgY = 0;
} else {
var width = this.width;
var imgX = 0;
var imgY = (this.height - this.width)/2;
}
tempCanvas.width = width;
tempCanvas.height = width;
tCtx.drawImage(imgTmp,imgX,imgY, width,width, 0,0, width, width);
// write on screen
var imgCroped = tempCanvas.toDataURL("image/png");
document.getElementById("fileAvatarImg").src = imgCroped;
};
imgTmp.src = e.target.result;
};
reader.readAsDataURL(this.files[0]);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment