@ixily/activ
Version:
Alpha Capture Trade Idea Verification. Blockchain ownership proven trade ideas and strategies.
118 lines (96 loc) • 2.53 kB
text/typescript
const BufferB = require('buffer/').Buffer
import { isNullOrUndefined } from '../../tools'
import { EnvModule } from './env.module'
let Jimp: any
type ImageType = 'profile' | 'banner'
const state = {
isBrowser: EnvModule.get('isBrowser'),
isNode: EnvModule.get('isNode'),
limitSizeLength: 100000,
}
const checks = {
JimpCheck: () => {
if (isNullOrUndefined(Jimp)) {
throw new Error('Jimp is not initialized')
}
},
}
const globalCheck = () => {
checks.JimpCheck()
}
const init = async (externalPackages: { JimpInstance: any }) => {
Jimp = externalPackages?.JimpInstance
}
const compressAndMinifyBase64 = async (
bufferStr?: string,
imageType?: ImageType,
bufferArray?: ArrayBuffer,
) => {
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?: string,
imageType?: ImageType,
) => {
const blob = await (await fetch(imageUrl as any)).blob()
const bufferArray = await blob.arrayBuffer()
imageUrl = await compressAndMinifyBase64(undefined, imageType, bufferArray)
return imageUrl
}
const convertOrMinifyImageToBase64 = async (
imageUrl?: string,
imageType?: ImageType,
) => {
globalCheck()
let data = imageUrl
if (!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: any) {
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 as string
}
export const ImagesModule = {
init,
convertOrMinifyImageToBase64,
}