File size: 1,592 Bytes
961cc99
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
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);