Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 612
Aidan Avatar asked Jul 19 '11 23:07

Aidan


People also ask

How do I get rid of white pixels?

Choose Layer > Matting > Defringe. For starters, try a setting of 1 pixel and click OK. At this point Photoshop goes off and replaces the white edge pixels with a mixture of the colours in the background and the colours in your object. If 1 pixel doesn't do the trick, then try Defringe again with either 2 or 3 pixels.

How do you get pixels on canvas?

To get the pixel of any specific portion from HTML canvas you can use the HTML canvas getImageData() Method. The getImageData() method usually returns an ImageData object that contains the pixel information of the specified object on the HTML canvas.

Which technique is used in each pixel to modify the values in a predefined neighborhood is?

Grayscaling and inverting colors. In this example we iterate over all pixels to change their values, then we put the modified pixel array back to the canvas using putImageData(). The invert function subtracts each color from the max value 255. The grayscale function uses the average of red, green and blue.


2 Answers

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).

like image 87
Gabriele Petrioli Avatar answered Oct 24 '22 21:10

Gabriele Petrioli


Instead of using a JPG, use a PNG with a transparent background around the image. You'll have a better result.

like image 38
Sahan Taraka Avatar answered Oct 24 '22 21:10

Sahan Taraka