Created
April 14, 2016 07:24
-
-
Save fujimura/7c7d7abfb8ef918fab7455326dc898fd to your computer and use it in GitHub Desktop.
Resize image in browser
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
const fileToDataUrl = (file) => { | |
return new Promise((resolve, reject) => { | |
const reader = new FileReader | |
reader.onload = (e) => { | |
resolve(e.target.result) | |
}; | |
reader.readAsDataURL(file); | |
}); | |
} | |
const resize = (file) => { | |
const MAX_WIDTH = 1024; | |
const MAX_HEIGHT = 1280; | |
let img = new window.Image | |
return new Promise((resolve, reject) => { | |
fileToDataUrl(file).then((dataUrl) => { | |
img.src = dataUrl; | |
img.onload = () => { | |
let width = img.width; | |
let height = img.height; | |
let canvas = document.createElement("canvas"); | |
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; | |
var ctx = canvas.getContext("2d"); | |
ctx.drawImage(img, 0, 0, width, height); | |
console.log(canvas) | |
console.log(file.type) | |
canvas.toBlob(resolve, file.type); | |
} | |
}); | |
}); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment