/** * 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')); } }) }