2012-03-06 5 views
1

이미지의 색상을 변경하는 스크립트를 만들려고하는데 색상을 변경하는 방법을 찾았지만 이미지에 흰색 배경이 있기 때문에 모든 이미지가 변경되므로 어떻게 든 흰색 픽셀을 무시할 수 있습니까? 당신을 위해이 일 같은캔버스에 흰색 픽셀을 투명하게 만드시겠습니까?

<!doctype html> 
<html> 
<head> 

</head> 

<body> 
<h4>Original Image</h4> 
<img id="testImage" src='../src/test.png'/> 

<h4>Image copied to canvas</h4> 
<canvas id="canvas" width="500" height="500"></canvas> 

<h4>Modified Image copied to an image tag</h4> 
<img id="imageData"/> 

<script> 

var canvas = document.getElementById("canvas"), 
ctx = canvas.getContext("2d"), 
image = document.getElementById("testImage"); 

ctx.drawImage(image,0,0); 

var imgd = ctx.getImageData(0, 0, 128, 128), 
    pix = imgd.data, 
    uniqueColor = [0,0,150]; // Blue for an example, can change this value to be anything. 

// Loops through all of the pixels and modifies the components. 
for (var i = 0, n = pix.length; i <n; i += 4) { 
     pix[i] = uniqueColor[0]; // Red component 
     pix[i+1] = uniqueColor[1]; // Blue component 
     pix[i+2] = uniqueColor[2]; // Green component 
     //pix[i+3] is the transparency. 
} 

ctx.putImageData(imgd, 0, 0); 


var savedImageData = document.getElementById("imageData"); 
savedImageData.src = canvas.toDataURL("image/png"); 
</script> 
</body> 
</html> 
+0

@aglassman의 답변을 사용하려고합니다. 그러나 이미지를위한 캔버스 요소를 만들고 시작시이를 처리하십시오. 그런 다음 캔버스 요소를 캔버스에 그립니다. 이렇게하면 성능이 크게 향상됩니다. –

답변

2

겠습니까 뭔가 :

이 지금까지 코드는?

if (pix[i] == 255 && 
     pix[i+1] == 255 && 
     pix[i+2] == 255) 
    { 
    //pixel is white 
    } 
    else 
    { 
    //pixel is not white, modify it. 
    } 
+0

나는 그것을 작동 시키려고 노력했다, doesnt는 속임수를 할 것 같다. (나는 전문가가 잘못 붙어있을 수도있다.) 어떻게 그 코드 조각을 놓을 까? – justanotherhobbyist

+0

죄송합니다. 이제 코드를 작성해 주시면됩니다. 넌 정말 대단해. 고마워. – justanotherhobbyist

+0

일부 이미지에서는 작동하지만 다른 이미지에서는 이상하게 작동합니다. 웹에서 이미지를 얻을 때 작동하지 않는 것 같습니다. – justanotherhobbyist

관련 문제