728x90
반응형
흰색배경에 서명이 있는 PNG 이미지에서 흰색배경 제거는 어떻게 할까요?
가장 간단하고 깔끔하게 작업한 내용을 공유합니다.
아래코드는 jimp 모듈을 이용하여 사용하였습니다. jimp 모듈은 이미지처리 모듈이며 의존성 있는 다른 모듈이 없어서 설치 및 사용에 매우 용의 합니다. 파일도 읽는 함수도 포함되어 있어서 모듈만 설치하면 바로 적용할 수 있습니다.
const Jimp = require('jimp');
async function run (){
try{
Jimp.read('sign.png')
.then(image => {
// 이미지에 알파 채널 추가
image.rgba(true);
//이미지 자르기
image.autocrop();
//흰색 제거
image.scan(0, 0, image.bitmap.width, image.bitmap.height, function(x, y, idx) {
// 흰색 픽셀 제거
if (this.bitmap.data[idx] === 255 && this.bitmap.data[idx+1] === 255 && this.bitmap.data[idx+2] === 255) {
this.bitmap.data[idx+3] = 0; // alpha 값을 0으로 설정하여 투명하게 만듦
}
});
// 이미지 저장
image.write('output.png');
})
.catch(err => {
console.error(err);
});
}catch(err){
console.log({err})
}
}
// Import the image
run();
참고자료
https://www.npmjs.com/package/jimp
jimp
An image processing library written entirely in JavaScript (i.e. zero external or native dependencies). Latest version: 0.22.7, last published: 18 days ago. Start using jimp in your project by running `npm i jimp`. There are 1938 other projects in the npm
www.npmjs.com

728x90
반응형