UNPKG

@paroicms/server-image-cache-engine

Version:

The image variant engine that we use at Paroi.

71 lines 3.05 kB
import { nbVal } from "@paroi/data-formatters-lib"; import { isResizeRule } from "@paroicms/public-anywhere-lib"; export function computeImageVariantSize({ sourceImage, rawResizeR, autoCrop, }) { if (!isResizeRule(rawResizeR)) { throw new Error(`This image size ${rawResizeR} is not handled.`); } const splitted = rawResizeR.split("x"); if (splitted.length === 3) { const value = splitted[1]; if (sourceImage.rawHeight > sourceImage.rawWidth) { rawResizeR = `x${value}`; } else if (sourceImage.rawWidth > sourceImage.rawHeight) { rawResizeR = `${value}x`; } else { rawResizeR = `${value}x`; } } const [rawWidth, rawHeight] = rawResizeR.split("x"); const v = { width: rawWidth === "" ? undefined : nbVal(rawWidth), height: rawHeight === "" ? undefined : nbVal(rawHeight), }; if (v.height !== undefined && v.width !== undefined) { return toParsedResizeRuleWithVariant(reduceSizeIfNecessary({ rawWidth: v.width, rawHeight: v.height }, sourceImage)); } const autoCropAvg = autoCrop && sourceImage.avgRawHeight !== undefined && sourceImage.avgRawWidth !== undefined ? { width: sourceImage.avgRawWidth, height: sourceImage.avgRawHeight, } : undefined; if (v.width !== undefined && v.height === undefined) { const targetHeight = autoCropAvg ? Math.round((v.width * autoCropAvg.height) / autoCropAvg.width) : Math.round((v.width * sourceImage.rawHeight) / sourceImage.rawWidth); return toParsedResizeRuleWithVariant(reduceSizeIfNecessary({ rawWidth: v.width, rawHeight: targetHeight }, sourceImage)); } if (v.height !== undefined && v.width === undefined) { const targetWidth = autoCropAvg ? Math.round((v.height * autoCropAvg.width) / autoCropAvg.height) : Math.round((v.height * sourceImage.rawWidth) / sourceImage.rawHeight); return toParsedResizeRuleWithVariant(reduceSizeIfNecessary({ rawWidth: targetWidth, rawHeight: v.height }, sourceImage)); } throw new Error(`Invalid variant '${rawResizeR}'`); } function reduceSizeIfNecessary(preferredSize, actualSize) { const diffW = actualSize.rawWidth - preferredSize.rawWidth; const diffH = actualSize.rawHeight - preferredSize.rawHeight; if (diffW >= 0 && diffH >= 0) { return preferredSize; } if (diffW < diffH) { return { rawWidth: actualSize.rawWidth, rawHeight: Math.round((actualSize.rawWidth * preferredSize.rawHeight) / preferredSize.rawWidth), }; } return { rawWidth: Math.round((actualSize.rawHeight * preferredSize.rawWidth) / preferredSize.rawHeight), rawHeight: actualSize.rawHeight, }; } function toParsedResizeRuleWithVariant(size) { return { ...size, rawSizeName: `${size.rawWidth}x${size.rawHeight}`, }; } //# sourceMappingURL=compute-variant-size.js.map