| Server IP : 217.154.3.148 / Your IP : 216.73.216.90 Web Server : Apache System : Linux blissful-wright.217-154-3-148.plesk.page 6.8.0-124-generic #124-Ubuntu SMP PREEMPT_DYNAMIC Tue May 26 13:00:45 UTC 2026 x86_64 User : gracious-boyd_hfhh1h8vo9n ( 10000) PHP Version : 8.3.31 Disable Function : opcache_get_status MySQL : OFF | cURL : ON | WGET : OFF | Perl : OFF | Python : OFF | Sudo : OFF | Pkexec : OFF Directory : /var/www/vhosts/gracious-boyd.217-154-3-148.plesk.page/nextjs/lib/ |
Upload File : |
import sharp from 'sharp'
function dataUrlToBuffer(dataUrl: string): Buffer {
const match = dataUrl.match(/^data:image\/png;base64,(.+)$/)
if (!match) {
throw new Error('Expected PNG data URL')
}
return Buffer.from(match[1], 'base64')
}
export type MaskStats = {
width: number
height: number
coverage: number
mean: number
}
export async function maskStatsFromDataUrl(dataUrl: string): Promise<MaskStats> {
const buf = dataUrlToBuffer(dataUrl)
const image = sharp(buf)
const meta = await image.metadata()
if (!meta.width || !meta.height) {
throw new Error('mask missing dimensions')
}
const { data } = await image.ensureAlpha().raw().toBuffer({ resolveWithObject: true })
const pixels = meta.width * meta.height
let alphaSum = 0
let solid = 0
let lumSum = 0
let solidLum = 0
let alphaVaries = false
for (let i = 3; i < data.length; i += 4) {
const r = data[i - 3]
const g = data[i - 2]
const b = data[i - 1]
const alpha = data[i]
alphaSum += alpha
if (alpha >= 128) solid += 1
const lum = Math.round((r + g + b) / 3)
lumSum += lum
if (lum >= 128) solidLum += 1
if (alpha !== 255) alphaVaries = true
}
if (!alphaVaries) {
return {
width: meta.width,
height: meta.height,
coverage: pixels > 0 ? solidLum / pixels : 0,
mean: pixels > 0 ? lumSum / (pixels * 255) : 0,
}
}
return {
width: meta.width,
height: meta.height,
coverage: pixels > 0 ? solid / pixels : 0,
mean: pixels > 0 ? alphaSum / (pixels * 255) : 0,
}
}