Skip to content

Instantly share code, notes, and snippets.

@VMBindraban
Created December 9, 2015 13:13
Show Gist options
  • Save VMBindraban/1be9cd5eceb347bef860 to your computer and use it in GitHub Desktop.
Save VMBindraban/1be9cd5eceb347bef860 to your computer and use it in GitHub Desktop.
Resize/crop/center in javascript through canvas to base64
var $uplImageBtn = $('.pui--ev-upload'),
$uplContainer = $('#uplProfileImg'),
$previewImg = $('.macc--s-pimg img');
$uplImageBtn.click(function() {
$uplContainer.trigger('click');
});
$uplContainer.on('change', function() {
if (!this.files && !this.files[0]) {
return;
}
var reader = new FileReader(),
tmpImg = '';
reader.onload = function (e) {
$previewImg.attr('src', snapshotResize(e.target.result, 380, 285));
}
reader.readAsDataURL(this.files[0]);
});
function snapshotResize (srcData, width, height) {
var imageObj = new Image(),
canvas = document.createElement("canvas"),
ctx = canvas.getContext('2d'),
xStart = 0,
yStart = 0,
aspectRadio,
newWidth,
newHeight;
imageObj.src = srcData;
canvas.width = width;
canvas.height = height;
aspectRadio = imageObj.height / imageObj.width;
if(imageObj.height < imageObj.width) {
//horizontal
aspectRadio = imageObj.width / imageObj.height;
newHeight = height,
newWidth = aspectRadio * height;
xStart = -(newWidth - width) / 2;
} else {
//vertical
newWidth = width,
newHeight = aspectRadio * width;
yStart = -(newHeight - height) / 2;
}
ctx.drawImage(imageObj, xStart, yStart, newWidth, newHeight);
return canvas.toDataURL("image/jpeg", 0.75);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment