fix(aklive2d): handle premultiplied alpha in live2d pngs

This commit is contained in:
Haoyu Xu
2023-11-01 14:58:48 -04:00
parent f6ac6d600d
commit 82621d90e6
2 changed files with 12 additions and 409 deletions

View File

@@ -29,7 +29,18 @@ export default class AlphaComposite {
}
async toBuffer(filename, extractedDir) {
return await sharp(path.join(extractedDir, filename)).toBuffer()
const file = path.join(extractedDir, filename)
const { data, info } = await sharp(file).raw().toBuffer({ resolveWithObject: true })
const { width, height, channels } = info;
const pixelArray = new Uint8ClampedArray(data.buffer);
for (let i = 0; i < pixelArray.length; i += 4) {
let alpha = pixelArray[i + 3] / 255;
pixelArray[i + 0] = pixelArray[i + 0] * alpha
pixelArray[i + 1] = pixelArray[i + 1] * alpha
pixelArray[i + 2] = pixelArray[i + 2] * alpha
}
return await sharp(pixelArray, { raw: { width, height, channels } }).png().toBuffer();
}
}