Skip to content

Instantly share code, notes, and snippets.

@nagiyevelchin
Created September 1, 2019 12:52
Show Gist options
  • Save nagiyevelchin/5374bd904aa2e41308f4dc5fa54fa535 to your computer and use it in GitHub Desktop.
Save nagiyevelchin/5374bd904aa2e41308f4dc5fa54fa535 to your computer and use it in GitHub Desktop.
Resizing image in user side in Vue CLI JavaScript
/**
* Resizing image in user side
* @param {string} filePath - file input value
* @param {number} [max_width=1600] - result image max width
* @param {number} [max_height=900] - result image max height
* @returns {Promise<base64string>}
*/
export default (filePath, max_width, max_height) => {
/**
* Example
* import imageResize from 'image-resize'
* ...
* methods: {
* fileInputChange: function (object) {
* const file = object.target.files[0];
* imageResize(file).then(fileB64 => {
* console.log(fileB64); // resized image in base 64 encoding
* });
* }
* }
* ...
*/
return new Promise((resolve, reject) => {
const canvas = document.createElement("canvas");
if (canvas.getContext) {//checking if canvas object supported in browser
const img = document.createElement("img");
img.src = window.URL.createObjectURL(filePath);
img.onload = function () {
window.URL.revokeObjectURL(this.src);
if (!max_width) {
max_width = 1600;
}
if (!max_height) {
max_height = 900;
}
let width = img.width;
let height = img.height;
if (width > max_width) {
height *= max_width / width;
width = max_width;
}
if (height > max_height) {
width *= max_height / height;
height = max_height;
}
canvas.width = width;
canvas.height = height;
const ctx = canvas.getContext("2d");
ctx.drawImage(img, 0, 0, width, height);
resolve(canvas.toDataURL('image/jpeg', .9));
}
} else {
reject(new Error('Canvas not supported'));
}
})
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment