Skip to content

Instantly share code, notes, and snippets.

@fujimura
Created April 14, 2016 07:24
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save fujimura/7c7d7abfb8ef918fab7455326dc898fd to your computer and use it in GitHub Desktop.
Save fujimura/7c7d7abfb8ef918fab7455326dc898fd to your computer and use it in GitHub Desktop.
Resize image in browser
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