Canvas ImageData removes white pixels

I have several images in html that have a white background. I need to remove the white background. I thought I could make all white pixels transparent, but I don't know how to do it. I would like to use html / javascript.

+6
source share
4 answers

Here's 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 image to the return 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 come from the same domain as the code (for security reasons).

+13
source

Instead of using jpg, use PNG with a transparent background around the image. You will have a better result.

+1
source

Well, the image data that you return from the canvas object using "getImageData" is just RGBA pixel information, that is, red, green, blue and alpha transparency. This way you can get the image data and just iterate over it, looking at four pixels at a time. When you see white, you can simply zero it out (along with the alpha value).

Now the fact is that you will not be satisfied with the results, because there will still be a β€œhalo” around non-white elements. The original image is (possibly) slightly blurry, smoothes efficiently, along the edges of the colored areas. Thus, at the edges there are pixels that are slightly lighter than the main image, and you will see them even after removing all the white ones.

To really clear the edges is quite difficult, depending on what kind of source images you have. I do not think that this is advanced image processing or something else, but it is not trivial.

0
source

But if you want to just clear imageData before drawing, this will be 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; } } 
0
source

Source: https://habr.com/ru/post/893115/


All Articles