Skip to content

Instantly share code, notes, and snippets.

@jmshal
Last active April 27, 2024 04:15
Show Gist options
  • Select an option

  • Save jmshal/9ccd7fce7eefb63cd118a217636e31a6 to your computer and use it in GitHub Desktop.

Select an option

Save jmshal/9ccd7fce7eefb63cd118a217636e31a6 to your computer and use it in GitHub Desktop.
npm i --save gist:9ccd7fce7eefb63cd118a217636e31a6
'use strict';
/**
* Resize an image (from URL). Ensures that the images is contained within the bounding box.
*
* @param {string} url The image URL
* @param {number} width The maximum image width
* @param {number} height The maximum image height
* @param {boolean} [padding] Whether to include padding if the image doesn't fit perfectly
* @returns {Promise<string>}
*/
function resizeImage(url, width, height, padding = false) {
return new Promise((resolve, reject) => {
const image = new Image();
image.onload = image.onerror = function (event) {
if (event.type === 'error') {
return reject(new Error('Unable to load image - ' + url));
}
try {
const ratio = Math.min(width / image.naturalWidth, height / image.naturalHeight);
const canvas = document.createElement('canvas');
const ctx = canvas.getContext('2d');
const imageWidth = image.naturalWidth * ratio;
const imageHeight = image.naturalHeight * ratio;
const canvasWidth = canvas.width = padding ? width : imageWidth;
const canvasHeight = canvas.height = padding ? height : imageHeight;
ctx.drawImage(image, (canvasWidth - imageWidth) / 2, (canvasHeight - imageHeight) / 2, imageWidth, imageHeight);
resolve(canvas.toDataURL());
} catch(err) {
reject(err);
}
};
image.setAttribute('crossOrigin', 'anonymous');
image.src = url;
});
}
module.exports = resizeImage;
{
"name": "resize-image",
"version": "1.0.0",
"description": "A simple commonjs function which resizes an image to specific dimensions."
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment