UNPKG

@widergy/web-utils

Version:
69 lines (68 loc) 2.46 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.fetchImages = exports.fetchImage = exports.resizeImage = void 0; const srcToFile = async (src, fileName, imageResizingConfig) => { const response = await fetch(src); if (response.ok && response.url) { const buffer = await response.arrayBuffer(); return new File([buffer], fileName, { type: imageResizingConfig.imageType }); } }; const scaleImage = async (img, fileName, imageResizingConfig) => { const canvas = document.createElement('canvas'); let ctx = canvas.getContext('2d'); ctx.drawImage(img, 0, 0); let { width, height } = img; if (width > height) { if (width > imageResizingConfig.maxWidth) { height *= imageResizingConfig.maxWidth / width; width = imageResizingConfig.maxWidth; } } else if (height > imageResizingConfig.maxHeight) { width *= imageResizingConfig.maxHeight / height; height = imageResizingConfig.maxHeight; } canvas.width = width; canvas.height = height; ctx = canvas.getContext('2d'); ctx.drawImage(img, 0, 0, width, height); const imageData = canvas.toDataURL(imageResizingConfig.imageType); const file = await srcToFile(imageData, fileName, imageResizingConfig); return file; }; const resizeImage = (file, imageResizingConfig = { maxWidth: 1000, maxHeight: 1000, imageType: 'image/png' }) => { return new Promise((resolve, reject) => { const img = document.createElement('img'); const reader = new FileReader(); reader.onload = (e) => { img.src = e.target.result; img.onload = async () => { const scaledFile = scaleImage(img, file.name, imageResizingConfig); resolve(scaledFile); }; }; reader.onerror = reject; reader.readAsDataURL(file); }); }; exports.resizeImage = resizeImage; const fetchImage = (url) => new Promise(resolve => { const img = new Image(); img.onload = () => resolve(); img.onerror = () => resolve(); img.src = url; }); exports.fetchImage = fetchImage; const fetchImages = (urls) => Promise.all(urls.map(exports.fetchImage)); exports.fetchImages = fetchImages; const IMAGE_UTILS = { resizeImage: exports.resizeImage, fetchImage: exports.fetchImage, fetchImages: exports.fetchImages }; exports.default = IMAGE_UTILS;