/** * # Image Input Element to Base 64 */ export default async function imageInputToBase64({ imageInput, maxWidth, mimeType, }) { var _a, _b; /** * Make https request * * @description make a request to datasquirel.com */ try { let imagePreviewNode = document.querySelector(`[data-imagepreview='image']`); let imageName = (_a = imageInput.files) === null || _a === void 0 ? void 0 : _a[0].name.replace(/\..*/, ""); let imageDataBase64; const MIME_TYPE = mimeType ? mimeType : "image/jpeg"; const QUALITY = 0.95; const MAX_WIDTH = maxWidth ? maxWidth : null; const file = (_b = imageInput.files) === null || _b === void 0 ? void 0 : _b[0]; const blobURL = file ? URL.createObjectURL(file) : undefined; const img = new Image(); if (blobURL) { img.src = blobURL; imageDataBase64 = await new Promise((res, rej) => { /** ********************* Handle Errors in loading image */ img.onerror = function () { URL.revokeObjectURL(this.src); window.alert("Cannot load image!"); }; img.onload = function (e) { const imgEl = e.target; URL.revokeObjectURL(imgEl.src); const canvas = document.createElement("canvas"); if (MAX_WIDTH) { const scaleSize = MAX_WIDTH / img.naturalWidth; canvas.width = img.naturalWidth < MAX_WIDTH ? img.naturalWidth : MAX_WIDTH; canvas.height = img.naturalWidth < MAX_WIDTH ? img.naturalHeight : img.naturalHeight * scaleSize; } else { canvas.width = img.naturalWidth; canvas.height = img.naturalHeight; } const ctx = canvas.getContext("2d"); ctx === null || ctx === void 0 ? void 0 : ctx.drawImage(img, 0, 0, canvas.width, canvas.height); const srcEncoded = canvas.toDataURL(MIME_TYPE, QUALITY); if (imagePreviewNode) { document .querySelectorAll(`[data-imagepreview='image']`) .forEach((_img) => { const _imgEl = _img; _imgEl.src = srcEncoded; }); } res(srcEncoded); }; }); return { imageBase64: imageDataBase64 === null || imageDataBase64 === void 0 ? void 0 : imageDataBase64.replace(/.*?base64,/, ""), imageBase64Full: imageDataBase64, imageName: imageName, }; } else { return {}; } } catch ( /** @type {*} */error) { console.log("Image Processing Error! =>", error.message); return {}; } }