Home > Enterprise >  How to remove a background of a JPG image given another PNG image with an object in it?
How to remove a background of a JPG image given another PNG image with an object in it?

Time:12-06

For example, I have a PNG image where there is an object I need (not transparent) and a background area (transparent). I would like to cut the same object (non-transparent area) from another JPG image to a new PNG.

let jpg = d3.select("#myJpg"); 
let png = d3.select("#myPng");

// cut object of png from jpg 

CodePudding user response:

Using canvas you can cut out on image using another, but there are some serious restrictions here (your image needs to be hosted on your server or have the correct CORS header for you canvas to export data - if you don't need to export the image to a DataURL it should be fine).

void async function(){

  const canvas = document.createElement( 'canvas' );
  const ctx = canvas.getContext( '2d' );
  const firstImage = await testImageSquare( 400, 400, 200, 'red' );
  const secondImage = await testImageSquare( 400, 400, 100, 'green' );

  canvas.width = firstImage.naturalWidth;
  canvas.height = firstImage.naturalHeight;

  ctx.drawImage( firstImage, 0, 0 );
  ctx.globalCompositeOperation = 'source-in';
  ctx.drawImage( secondImage, 0, 0 );

  document.body.append( firstImage, secondImage, canvas );

}();

/** Helper method to create images */
async function testImageSquare( width, height, squareSize, fillStyle ){

  const canvas = document.createElement( 'canvas' );
  const ctx = canvas.getContext( '2d' );
  
  canvas.width = width;
  canvas.height = height;
  
  ctx.fillStyle = fillStyle;
  ctx.fillRect( (width - squareSize) / 2, (height - squareSize) / 2, squareSize, squareSize );
  
  const image = new Image;
  
  image.src = canvas.toDataURL();
  
  await new Promise(r => image.addEventListener( 'load', r ));
  
  return image;
  
}
img, canvas {
  border: 1px solid black;
}

  • Related