I'm trying to change all black colors of my image into transparency in jimp js
I've done a lot of research on the subject and so far nothing, so I decided to come here and ask this question
There is a snippet in github's issue, I've changed some parts for your case:
import Jimp from 'jimp'; Jimp.read('./sample.png').then(image => { const targetColor = {r: 0, g: 0, b: 0, a: 255}; // black const replaceColor = {r: 0, g: 0, b: 0, a: 0}; // transparent const colorDistance = (c1, c2) => Math.sqrt(Math.pow(c1.r - c2.r, 2) + Math.pow(c1.g - c2.g, 2) + Math.pow(c1.b - c2.b, 2) + Math.pow(c1.a - c2.a, 2)); // Distance between two colors const threshold = 32; image.scan(0, 0, image.bitmap.width, image.bitmap.height, (x, y, idx) => { const thisColor = { r: image.bitmap.data[idx + 0], g: image.bitmap.data[idx + 1], b: image.bitmap.data[idx + 2], a: image.bitmap.data[idx + 3] }; if(colorDistance(targetColor, thisColor) <= threshold) { image.bitmap.data[idx + 0] = replaceColor.r; image.bitmap.data[idx + 1] = replaceColor.g; image.bitmap.data[idx + 2] = replaceColor.b; image.bitmap.data[idx + 3] = replaceColor.a; } }); image.write('transparent.png'); });
There is a snippet in github's issue, I've changed some parts for your case: