-
-
Save williampaulo/e5f7d64e91ed76e3a369343848d282d9 to your computer and use it in GitHub Desktop.
Resize/crop/center in javascript through canvas to base64
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
| 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