Converting White Background To Transparent

Do you have an image with a white background and you want to remove that whiteness and replace it with transparency? Here is a basic example using jimp on Node.js.

Start by installing jimp:
npm install jimp

Create your script file (e.g. app.js)

const jimp = require("jimp");

function turnIt(image, targetColor, replaceColor, threshold){

  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
    
  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;
    }
  });
}


// Replace colors under this threshold. The smaller the number, the more specific it is.
	
threshold = 80;

await jimp.read('my_image.png').then(image => {
  //remove whitish colors
  turnIt(image, {r: 255, g: 255, b: 255, a:255}, {r: 255, g: 255, b: 255, a: 0}, threshold);

	image.write('my_new_image.png');
});


Replace your *my_image.png* and execute your node app.js The resulting images will be in png as it supports transparent pixels.

In my case of usage, this was part of a project of digitization, where the first step consisted in treating the background.

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *