UNPKG

@self.id/image-utils

Version:

Image utilities for Self.ID profiles

47 lines (46 loc) 1.95 kB
const DEFAULT_DIMENSIONS = { height: 512, width: 512 }; function selectCover(options, { height , width }) { let selected = null; for (const option of options){ if (option.height >= height && option.width >= width && (selected === null || selected.size != null && option.size != null && option.size < selected.size || option.height * option.width < selected.height * selected.width)) { selected = option; } } return selected; } function selectContain(options, { height , width }) { let selected = null; for (const option of options){ if (option.height <= height && option.width <= width && (selected === null || selected.size != null && option.size != null && option.size < selected.size || option.height * option.width > selected.height * selected.width)) { selected = option; } } return selected; } /** Select the best option from the given `sources` to match the wanted `dimensions` and `mode`. */ export function selectImageSource(sources, dimensions, mode = 'cover') { let alternative = null; if (Array.isArray(sources.alternatives)) { alternative = mode === 'cover' ? selectCover(sources.alternatives, dimensions) : selectContain(sources.alternatives, dimensions); } return alternative ?? sources.original; } /** @internal */ export function getDimensions(image, dimensions = DEFAULT_DIMENSIONS, mode = 'cover') { let width = image.width; let height = image.height; if (mode === 'contain' && width >= height || mode === 'cover' && width <= height) { if (width >= dimensions.width) { height = Math.round(height * dimensions.width / width); width = dimensions.width; } } else if (height > dimensions.height) { width = Math.round(width * dimensions.height / height); height = dimensions.height; } return { width, height }; }