Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
126
rated 0 times [  129] [ 3]  / answers: 1 / hits: 31587  / 12 Years ago, fri, july 13, 2012, 12:00:00

If I load an image, how can I loop through all its pixels and turn the white ones (or which ever color I specify) to be turned transparent?



I have an idea on how to do this, but the looping process should be like a 2d array, so it would involve two for loops.



I was thinking I would start on the top row first pixel, iterating to the right, if its a white pixel, then i turn it transparent, and move 1 pixel to the right, if its not white, then I stop. Then in the same row, I start from the left most pixel, and check, if white, I turn it transparent, then move 1 pixel to the left, etc, etc...



Then I move 1 row down and repeat the whole process..



This way I don't remove any white pixels in the actual image.


More From » html

 Answers
5

Its pretty simple to do using getImageData and putImageData just note you can take a pretty significant hit on performance the larger the image gets. You just need to determine if the current pixel is white, then change its alpha to 0.



Live Demo



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

canvas.height = canvas.width = 135;
ctx.drawImage(image,0,0);

var imgd = ctx.getImageData(0, 0, 135, 135),
pix = imgd.data,
newColor = {r:0,g:0,b:0, a:0};

for (var i = 0, n = pix.length; i <n; i += 4) {
var r = pix[i],
g = pix[i+1],
b = pix[i+2];

// If its white then change it
if(r == 255 && g == 255 && b == 255){
// Change the white to whatever.
pix[i] = newColor.r;
pix[i+1] = newColor.g;
pix[i+2] = newColor.b;
pix[i+3] = newColor.a;
}
}

ctx.putImageData(imgd, 0, 0);​


It was also asked if you could make the values sort of fuzzy to check. Its really easy, just check if its in a certain range. The following will turn off white to pure white transparent.



 // If its white or close then change it
if(r >=230 && g >= 230 && b >= 230){
// Change the white to whatever.
pix[i] = newColor.r;
pix[i+1] = newColor.g;
pix[i+2] = newColor.b;
pix[i+3] = newColor.a;
}


More resources




[#84273] Thursday, July 12, 2012, 12 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
tai

Total Points: 466
Total Questions: 87
Total Answers: 116

Location: Saint Helena
Member since Tue, Nov 3, 2020
4 Years ago
;