Skip to content

Instantly share code, notes, and snippets.

@jagomf
Last active September 29, 2018 17:47
Show Gist options
  • Save jagomf/078c47ba9198070d82a470cb029c596c to your computer and use it in GitHub Desktop.
Save jagomf/078c47ba9198070d82a470cb029c596c to your computer and use it in GitHub Desktop.
Resizes a base64 image to a specified maximum largest dimension (whether width or height)
/**
* Resizes a picture to a maximum length/width (based on largest dimension)
* @param {string} original Base64 representation of image to be resized.
* @param {number} maxSize Amount of pixels that largest dimention (whether width or length) should have.
* @param {string} finalMimeType Mime type of the resulting resized image.
* @returns {Promise} A Promise that resolves with resized picture.
*/
resizeImage(original, maxSize, finalMimeType = 'image/jpeg') {
return new Promise(resolve => {
const image = new Image();
image.onload = () =>
{
// Resize the image
const canvas = document.createElement('canvas');
let width = image.width,
height = image.height;
if (width > height && width > maxSize)
{
height *= maxSize / width;
width = maxSize;
}
else if (height > maxSize)
{
width *= maxSize / height;
height = maxSize;
}
canvas.width = width;
canvas.height = height;
canvas.getContext('2d').drawImage(image, 0, 0, width, height);
const base64str = canvas.toDataURL(finalMimeType);
resolve(base64str);
};
image.src = original;
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment