yasd/apps/server/lib/util.js

60 lines
1.4 KiB
JavaScript

const path = require('path');
const sharp = require('sharp');
/**
* Generates a promise to fill the button image buffer
* @param {*} imgPath
* @param {*} iconSize
* @returns
*/
async function buttonImageToBuffer(imgPath, iconSize){
const buffer = await sharp(path.resolve(imgPath))
.flatten()
.resize(iconSize, iconSize)
.raw()
.toBuffer()
.catch( err => {
console.log(err)
})
return Promise.resolve(buffer);
}
/**
* Generates the buffer to fill the SD Panel
* @param {*} imgPath
* @param {*} iconSize
* @param {*} cols
* @param {*} rows
* @param {*} callback
*/
async function panelImageToBuffer(imgPath, iconSize, cols, rows, callback){
await sharp(path.resolve(imgPath))
.flatten()
.resize(iconSize*cols, iconSize*rows)
.raw()
.toBuffer()
.then( data => {
callback(data)
})
.catch( err => {
console.log(err)
callback(null)
})
}
/**
* https://stackoverflow.com/questions/5623838/rgb-to-hex-and-hex-to-rgb
* @param {hex color code} hex
* @returns Object with r g b values.
*/
function hexToRGB(hex){
var result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex);
return result ? {
r: parseInt(result[1], 16),
g: parseInt(result[2], 16),
b: parseInt(result[3], 16)
} : null;
}
module.exports = {buttonImageToBuffer, panelImageToBuffer, hexToRGB}