UNPKG

@mornya/react-image-libs

Version:
63 lines (62 loc) 2.23 kB
export function getImageSize(url, option) { return new Promise(function (resolve, reject) { var _a; var image = new Image(); var imageLoadHandler = function () { return resolve({ url: url, width: image.naturalWidth, height: image.naturalHeight, isComplete: image.complete, }); }; var imageErrorHandler = function (error) { if (option === null || option === void 0 ? void 0 : option.isIgnoreError) { resolve({ url: url, width: 0, height: 0, isComplete: false, }); } else { reject(error); } }; image.src = url; image.crossOrigin = 'anonymous'; image.addEventListener('load', imageLoadHandler, { once: true }); image.addEventListener('error', imageErrorHandler, { once: true }); setTimeout(function () { if (!image.complete) { if (option === null || option === void 0 ? void 0 : option.isIgnoreError) { resolve({ url: url, width: 0, height: 0, isComplete: false, }); } else { reject(new Error('Cannot load image by timeout!')); } } }, (_a = option === null || option === void 0 ? void 0 : option.timeout) !== null && _a !== void 0 ? _a : 2000); }); } export function getImageFileToData(file) { return new Promise(function (resolve, reject) { var fileReader = new FileReader(); fileReader.addEventListener('loadend', function (e) { var _a; if ((_a = e.target) === null || _a === void 0 ? void 0 : _a.error) { console.error(e.target.error); reject(new Error(e.target.error.name)); } else { resolve(String(fileReader.result)); } }, false); fileReader.readAsDataURL(file); }); }