forked from Simnation/Main
81 lines
No EOL
2.2 KiB
JavaScript
81 lines
No EOL
2.2 KiB
JavaScript
const fs = require('fs')
|
|
const Jimp = require('jimp')
|
|
const webp = require('webp-converter');
|
|
|
|
async function convertToWebP(inputPath) {
|
|
try {
|
|
if (!fs.existsSync(inputPath)) {
|
|
throw new Error(`File doesn't exist: ${inputPath}`);
|
|
}
|
|
|
|
const outputWebp = inputPath.replace(/\.png$/, '.webp');
|
|
|
|
await webp.cwebp(inputPath, outputWebp, "-lossless", "-mt");
|
|
return outputWebp;
|
|
} catch (err) {
|
|
console.error(`[convertToWebP] Error: ${err.message}`);
|
|
return null;
|
|
}
|
|
}
|
|
|
|
async function cleanImage(inputPath, outputPath, threshold = 150) {
|
|
if (!fs.existsSync(inputPath)) return false
|
|
try {
|
|
const img = await Jimp.read(inputPath)
|
|
const { width, height } = img.bitmap
|
|
|
|
const leftEx = Math.floor(width * 0.10)
|
|
const rightEx = Math.floor(width * 0.90)
|
|
const topEx = Math.floor(height * 0.10)
|
|
const bottomEx = Math.floor(height * 0.90)
|
|
|
|
let minX = width, minY = height, maxX = 0, maxY = 0
|
|
const bgR = 0, bgG = 255, bgB = 0
|
|
|
|
img.scan(0, 0, width, height, (x, y, idx) => {
|
|
if (x < leftEx || x > rightEx || y < topEx || y > bottomEx) {
|
|
img.bitmap.data[idx + 3] = 0
|
|
return
|
|
}
|
|
const r = img.bitmap.data[idx]
|
|
const g = img.bitmap.data[idx + 1]
|
|
const b = img.bitmap.data[idx + 2]
|
|
const dist = Math.sqrt((r - bgR) ** 2 + (g - bgG) ** 2 + (b - bgB) ** 2)
|
|
|
|
if (dist < threshold) {
|
|
img.bitmap.data[idx + 3] = 0
|
|
} else {
|
|
if (x < minX) minX = x
|
|
if (y < minY) minY = y
|
|
if (x > maxX) maxX = x
|
|
if (y > maxY) maxY = y
|
|
}
|
|
})
|
|
|
|
if (maxX > minX && maxY > minY) {
|
|
const w = maxX - minX + 1
|
|
const h = maxY - minY + 1
|
|
const m = 0.05
|
|
const exW = Math.floor(w * m)
|
|
const exH = Math.floor(h * m)
|
|
const cX = Math.max(0, minX - exW)
|
|
const cY = Math.max(0, minY - exH)
|
|
const cW = Math.min(width - cX, w + exW * 2)
|
|
const cH = Math.min(height - cY, h + exH * 2)
|
|
img.crop(cX, cY, cW, cH)
|
|
}
|
|
|
|
await img.writeAsync(outputPath)
|
|
await convertToWebP(outputPath)
|
|
|
|
// Cancella l'immagine originale (non-webp)
|
|
fs.unlinkSync(inputPath)
|
|
|
|
return true
|
|
} catch (e) {
|
|
console.error(`[cleanImage] Error: ${e}`)
|
|
return false
|
|
}
|
|
}
|
|
|
|
exports('cleanImage', cleanImage); |