UNPKG

pomljs

Version:

Prompt Orchestration Markup Language

58 lines (54 loc) 1.75 kB
'use strict'; var sharp = require('sharp'); function readImage(src, base64) { if (src) { return sharp(src); } if (base64) { return sharp(Buffer.from(base64, 'base64')); } throw new Error('src or base64 is required'); } function resizeImage(image, metadata, maxWidth, maxHeight, resize) { let width = metadata.width || 1; let height = metadata.height || 1; const resizes = []; if (resize) { resizes.push(resize); } if (maxWidth) { resizes.push(maxWidth / width); } if (maxHeight) { resizes.push(maxHeight / height); } if (resizes.length === 0) { return image; } const resizeFactor = Math.min(...resizes); return image.resize(Math.round(width * resizeFactor), Math.round(height * resizeFactor)); } function convertType(image, metadata, type) { let fileType = metadata.format || ''; if (!fileType) { throw new Error('Cannot determine image format'); } if (type) { fileType = type.startsWith('image/') ? type.split('/', 2)[1] : type; image = image.toFormat(fileType); } return [image, fileType]; } async function preprocessImage(args) { const { src, base64, type, maxWidth, maxHeight, resize } = args; let sharpObj = readImage(src, base64); const metadata = await sharpObj.metadata(); const resizedImage = resizeImage(sharpObj, metadata, maxWidth, maxHeight, resize); const [converted, fileType] = convertType(resizedImage, metadata, type); return { base64: await converted.toBuffer().then(buffer => buffer.toString('base64')), mimeType: 'image/' + fileType }; } exports.preprocessImage = preprocessImage; //# sourceMappingURL=image.cjs.map