Created
July 6, 2017 06:42
-
-
Save bolerap/a7fe3241f2ede28faf62c94052abafef to your computer and use it in GitHub Desktop.
Temporary for issue https://github.com/bergben/ng2-img-tools/issues/7
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
| // helper functions | |
| private resizeImage(img, maxWidth, maxHeight, callback) { | |
| return img.onload = () => { | |
| // get image dimension | |
| let width = img.width; | |
| let height = img.height; | |
| // set width and height to the max values | |
| if (width > height) { | |
| if (width > maxWidth) { | |
| height *= maxWidth / width; | |
| width = maxWidth; | |
| } | |
| } else { | |
| if (height > maxHeight) { | |
| width *= maxHeight / height; | |
| height = maxHeight; | |
| } | |
| } | |
| // create canvas object | |
| let canvas = document.createElement('canvas'); | |
| // set canvas to the new calculated dimension values | |
| canvas.width = maxWidth; | |
| canvas.height = maxHeight; | |
| // create canvas context 2d and align image to center | |
| let startX = maxWidth / 2 - width / 2; | |
| let startY = maxHeight / 2 - height / 2; | |
| let ctx = canvas.getContext('2d', {alpha: false}); | |
| // draw image to canvas | |
| ctx.drawImage(img, startX, startY, width, height); | |
| // convert canvas to image | |
| let dataUrl = canvas.toDataURL('image/jpeg'); | |
| // run callback with result | |
| callback(dataUrl); | |
| }; | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment