UNPKG

react-native-template-mrf

Version:

54 lines (43 loc) 1.62 kB
const sharp = require('sharp') const fs = require('fs') const { promisify } = require('util') let config = {} const resizeFile = async ({ file, path, width, height, round = false }) => { const localFile = `./asset/${config.originalFile}` const targetFile = file || config.file if (!targetFile) { throw { message: 'No input file' } } const exists = promisify(fs.exists) if (!(await exists(localFile))) { throw { message: 'File not found' } } const destPath = [config.destinationPath, path].filter(e => !!e).join('/') if (!(await exists(destPath))) { await promisify(fs.mkdir)(destPath) } const outputFile = `${destPath}/${targetFile}.${config.extension}` const builder = await sharp(localFile).resize({ width, height }) if (round) { const hh = height || width const roundedCorners = Buffer.from(`<svg><rect x="0" y="0" width="${width}" height="${hh}" rx="${width / 2}" ry="${hh / 2}"/></svg>`) builder.composite([ { input: roundedCorners, blend: 'dest-in', }, ]) } console.log(`Converting ${localFile} to ${outputFile}...`) return builder.toFile(outputFile) } module.exports = { setConfig: ({ originalFile, destinationPath, file, extension = 'png' }) => { config = { originalFile, destinationPath, file, extension } }, resize: resizeFile, getStats: async file => { const stats = await sharp(file).metadata() return { ...stats, ratio: stats.width / stats.height } } }