/// 预乘Alpha操作 png才能使用 所以在使用前先判断通道是否是四个
async function manualPremultiplyAlpha(inputPath, outputPath) {
try {
// 读取图像为Raw格式
const { data, info } = await sharp(inputPath).raw().toBuffer({ resolveWithObject: true });
// 基于图像的宽度、高度和通道数进行遍历
const width = info.width;
const height = info.height;
const channels = info.channels;
if (channels !== 4) {
throw new Error('Input image must have 4 channels (RGBA).');
}
for (let y = 0; y < height; y++) {
for (let x = 0; x < width; x++) {
// Calculate the offset of the current pixel in the data array.
const pixelOffset = (y * width + x) * channels;
2 个回复
狂蜂浪蝶
赞同来自:
和2.x不一样,需要把-cl改成-cs
# png源文件方面
需要先预乘alpha之后再进行astc转换,具体可以用node的sharp库
具体代码如下
1567600631用户
赞同来自:
const fs = require('fs').promises;
/// 预乘Alpha操作 png才能使用 所以在使用前先判断通道是否是四个
async function manualPremultiplyAlpha(inputPath, outputPath) {
try {
// 读取图像为Raw格式
const { data, info } = await sharp(inputPath).raw().toBuffer({ resolveWithObject: true });
// 基于图像的宽度、高度和通道数进行遍历
const width = info.width;
const height = info.height;
const channels = info.channels;
if (channels !== 4) {
throw new Error('Input image must have 4 channels (RGBA).');
}
for (let y = 0; y < height; y++) {
for (let x = 0; x < width; x++) {
// Calculate the offset of the current pixel in the data array.
const pixelOffset = (y * width + x) * channels;
// 获取Alpha值并进行归一化(假设8位精度)
const alpha = data[pixelOffset + 3] / 255;
// 预乘Alpha操作
for (let c = 0; c < 3; c++) {
data[pixelOffset + c] = Math.round(data[pixelOffset + c] * alpha);
}
}
}
// 使用sharp处理预乘Alpha后的Buffer并输出为PNG
await sharp(Buffer.from(data), { raw: { width, height, channels } })
.png()
.toFile(outputPath);
console.log('Image processed and saved with manual pre-multiplied alpha.');
} catch (error) {
console.error('Error processing image:', error);
}
}
// 使用函数处理图像
const inputFilePath = 'k.png';
const outputFilePath = 'output.png';
manualPremultiplyAlpha(inputFilePath, outputFilePath);