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.
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.
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.
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.
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).
Instead of using a JPG, use a PNG with a transparent background around the image. You'll have a better result.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With