remote-rdr / scripts /white2transparent.js
shiveshnavin's picture
Update compo
961cc99
import sharp from 'sharp';
async function processImage(inputPath, outputPath) {
try {
// Read the input image as raw pixel data
const {data, info} = await sharp(inputPath)
.ensureAlpha()
.raw()
.toBuffer({resolveWithObject: true});
// Create a new buffer for the output image with RGBA data
const outputBuffer = Buffer.alloc(info.width * info.height * 4);
for (let i = 0; i < info.width * info.height; i++) {
const r = data[i * 4];
const g = data[i * 4 + 1];
const b = data[i * 4 + 2];
const a = data[i * 4 + 3]; // Original alpha
// Check if the pixel is pure white
if (r === 255 && g === 255 && b === 255) {
// Replace white with transparency
outputBuffer[i * 4] = r; // R
outputBuffer[i * 4 + 1] = g; // G
outputBuffer[i * 4 + 2] = b; // B
outputBuffer[i * 4 + 3] = 0; // A (fully transparent)
} else {
// Preserve the original color and alpha
outputBuffer[i * 4] = r;
outputBuffer[i * 4 + 1] = g;
outputBuffer[i * 4 + 2] = b;
outputBuffer[i * 4 + 3] = a;
}
}
// Write the processed image to a PNG file
await sharp(outputBuffer, {
raw: {
width: info.width,
height: info.height,
channels: 4,
},
}).toFile(outputPath);
console.log(`Image processed successfully and saved to ${outputPath}`);
} catch (error) {
console.error('Error processing image:', error);
}
}
// Example usage
const inputImagePath = 'public/icons-white.jpeg'; // Input image path
const outputImagePath = 'public/icons-white.png'; // Output image path
processImage(inputImagePath, outputImagePath);