Created
October 28, 2018 11:50
-
-
Save alieslamifard/3ac99b801710a2370f09bc409dde6290 to your computer and use it in GitHub Desktop.
resized base64 image in react
This file contains 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
getBase64 = (file, callback) => { | |
const reader = new FileReader(); | |
reader.addEventListener('load', e => { | |
const img = this.imgElement; | |
const canvas = this.canvasElement; | |
img.addEventListener('load', i => { | |
const image = i.target; | |
let ctx = canvas.getContext('2d'); | |
ctx.drawImage(img, 0, 0); | |
const MAX_WIDTH = 100; | |
const MAX_HEIGHT = 100; | |
let { width, height } = image; | |
if (width > height) { | |
if (width > MAX_WIDTH) { | |
height *= MAX_WIDTH / width; | |
width = MAX_WIDTH; | |
} | |
} else if (height > MAX_HEIGHT) { | |
width *= MAX_HEIGHT / height; | |
height = MAX_HEIGHT; | |
} | |
canvas.width = width; | |
canvas.height = height; | |
ctx = canvas.getContext('2d'); | |
ctx.drawImage(image, 0, 0, width, height); | |
const dataUrl = canvas.toDataURL(file.type); | |
image.src = 'data:image/gif;base64,R0lGODlhAQABAAAAACw='; | |
callback(dataUrl); | |
}); | |
img.src = e.target.result; | |
}); | |
reader.readAsDataURL(file); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment