Skip to content

Instantly share code, notes, and snippets.

@cameronmoreau
Created April 13, 2017 05:38
Show Gist options
  • Save cameronmoreau/499a32a3b07c246d0840c7e49d1d368f to your computer and use it in GitHub Desktop.
Save cameronmoreau/499a32a3b07c246d0840c7e49d1d368f to your computer and use it in GitHub Desktop.
Resize images on the web
import Promise from 'bluebird';
export const resizeImage = (image, maxWidth, maxHeight, quality) => {
const canvas = document.createElement('canvas');
let width = image.width;
let height = image.height;
if (width > height) {
if (width > maxWidth) {
height = Math.round(height * maxWidth / width);
width = maxWidth;
}
} else {
if (height > maxHeight) {
width = Math.round(width * maxHeight / height);
height = maxHeight;
}
}
canvas.width = width;
canvas.height = height;
const ctx = canvas.getContext('2d');
ctx.drawImage(image, 0, 0, width, height);
return canvas.toDataURL('image/jpeg', quality);
}
export const resize = (file, maxWidth, maxHeight) => {
return new Promise((resolve, reject) => {
const reader = new FileReader();
reader.readAsDataURL(file);
reader.onload = function (event) {
const dataUrl = event.target.result;
const image = new Image();
image.src = dataUrl;
image.onload = function () {
const resizedDataUrl = resizeImage(image, maxWidth, maxHeight, 0.8);
resolve(resizedDataUrl);
};
};
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment