hello

I need to create in javascript something to change a color to transparent, on PNG
I'd like to create a form that, when I post a picture, everything white should be transformed to transparent and generated as a new PNG, however this white is coming from a picture so it won't be exactly white
but contrast are good since this will pictures of text written on a white page
maybe some king of green screen algo

any ideas on how to do that ?

you are viewing a single comment's thread
view the rest of the comments
[–] 2 points 2 months ago

You can probably use getImageData, iterate over the data property, and check each pixel to see if it is close enough to white.

Pixel data is stored in groups of four: RGBA. So your loop will probably increment i += 4 to check each value of each pixel. You can adjust how much tolerance you want; 255 in RGB is white, so maybe you can check to see that data[i] >= 255 - tolerance where tolerance is some fairly small number, maybe 5. If data[i], data[i+1], and data[i+2] are all acceptably high, set the pixel in the new image to transparent. Otherwise, set it equal to the value of the original image.

This page has some examples of similar operations: https://pictureelement.github.io/html5tech/canvas-pixel-manipulation-and-animations.html

  • source