UNPKG

@ixily/activ

Version:

Alpha Capture Trade Idea Verification. Blockchain ownership proven trade ideas and strategies.

86 lines 2.9 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.ImagesModule = void 0; const BufferB = require('buffer/').Buffer; const tools_1 = require("../../tools"); const env_module_1 = require("./env.module"); let Jimp; const state = { isBrowser: env_module_1.EnvModule.get('isBrowser'), isNode: env_module_1.EnvModule.get('isNode'), limitSizeLength: 100000, }; const checks = { JimpCheck: () => { if ((0, tools_1.isNullOrUndefined)(Jimp)) { throw new Error('Jimp is not initialized'); } }, }; const globalCheck = () => { checks.JimpCheck(); }; const init = async (externalPackages) => { Jimp = externalPackages?.JimpInstance; }; const compressAndMinifyBase64 = async (bufferStr, imageType, bufferArray) => { const buff = bufferStr !== undefined ? BufferB.from(bufferStr.split(',')[1], 'base64') : bufferArray; const image = await Jimp.read(buff); let imageWidth = 0; let imageHeight = 0; if (imageType === 'profile') { imageWidth = 200; imageHeight = 200; } if (imageType === 'banner') { imageWidth = 400; imageHeight = 100; } const base64 = await image .resize(imageWidth, imageHeight) .quality(10) .getBase64Async(Jimp.MIME_PNG); return base64; }; const convertImageUrlToBase64 = async (imageUrl, imageType) => { const blob = await (await fetch(imageUrl)).blob(); const bufferArray = await blob.arrayBuffer(); imageUrl = await compressAndMinifyBase64(undefined, imageType, bufferArray); return imageUrl; }; const convertOrMinifyImageToBase64 = async (imageUrl, imageType) => { globalCheck(); let data = imageUrl; if (!(0, tools_1.isNullOrUndefined)(imageUrl)) { try { const isBase64 = imageUrl?.includes('base64,'); const imageLength = imageUrl?.length || 0; // console.log('convertOrMinifyImageToBase64 (isBase64)', isBase64) // console.log('convertOrMinifyImageToBase64 (imageLength)', imageLength) // is a base64 url if (isBase64 && imageLength > state.limitSizeLength) { data = await compressAndMinifyBase64(data, imageType); } // is a normal url then convert to base64 if (!isBase64) { data = await convertImageUrlToBase64(data, imageType); } } catch (error) { if (error.message.indexOf('Could not find MIME for Buffer') !== -1) { throw new Error('Provided image is not valid. Please make sure image URLs resolve to valid image files.'); } else { throw error; } } } return data; }; exports.ImagesModule = { init, convertOrMinifyImageToBase64, }; //# sourceMappingURL=images.module.js.map