canvas ImageData remove white pixels
I have some images in html that have a white background.开发者_开发百科 I need to remove the white background. I was thinking that I could make all white pixels transparent, but i dont know how to do that. I would only like to use html/javascript.
Here is how to do it..
function white2transparent(img)
{
var c = document.createElement('canvas');
var w = img.width, h = img.height;
c.width = w;
c.height = h;
var ctx = c.getContext('2d');
ctx.drawImage(img, 0, 0, w, h);
var imageData = ctx.getImageData(0,0, w, h);
var pixel = imageData.data;
var r=0, g=1, b=2,a=3;
for (var p = 0; p<pixel.length; p+=4)
{
if (
pixel[p+r] == 255 &&
pixel[p+g] == 255 &&
pixel[p+b] == 255) // if white then change alpha to 0
{pixel[p+a] = 0;}
}
ctx.putImageData(imageData,0,0);
return c.toDataURL('image/png');
}
and to use it set the src
of an image to the returned value of this method.
var someimage = document.getElementById('imageid');
someimage.src = white2transparent(someimage);
http://jsfiddle.net/gaby/UuCys/
For this code to work, the image must be coming from the same domain as the code (for security reasons).
Well the image data you get back from a canvas object with "getImageData" is just RGBA pixel information - that is, red, green, blue, and alpha transparency. Thus you could get the image data and just iterate through, looking at four pixels at a time. When you see a white one, you can just zero it out (along with the alpha value).
Now the thing is, you won't be satisfied with the results because there'll still be a "halo" around the non-white elements. The original image is (probably) slightly blurred, effectively anti-aliased, at the edges of colored areas. Thus there are pixels along the edges that are a little lighter than the main image, and you'll see those still after removing all the pure white ones.
To really clean up the edges is pretty tricky, depending on exactly what kind of source images you've got. I don't think it's cutting edge image processing or anything, but it's not trivial.
Instead of using a JPG, use a PNG with a transparent background around the image. You'll have a better result.
But if you want just clear the imageData before drawing there is a shorter solution :)
function clearData( imageData )
{
var d = imageData.data;
var L = d.length;
for ( var i = 3; i < L; i += 4 )
{
d[i] = 0;
}
}
精彩评论