Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

change color of image to greyscale in html5

I have a png image which I want to convert into grey scale. I managed to convert it into greyscale however it also changes the color for transparent ares of the image. How can I change its color without changing the transparent area of the image?

var canvas = document.getElementById('canvas');
var ctx = canvas.getContext('2d');
var img = new Image();
img.src = 'image.png';
ctx.drawImage(img, 0, 0);

var imageData = ctx.getImageData(0, 0, 420, 420);
var px = imageData.data;

var len = px.length;

for (var i = 0; i < len; i+=4) {
    var redPx = px[i];
    var greenPx = px[i+1];
    var bluePx = px[i+2];
    var alphaPx = px[i+3];

    var greyScale = redPx * .3 + greenPx * .59 + bluePx * .11;

    px[i] = greyScale;
    px[i+1] = greyScale;
    px[i+2] = greyScale;
    px[i+3] = greyScale;
}

ctx.putImageData(imageData, 0, 0);
like image 237
Om3ga Avatar asked Sep 26 '13 12:09

Om3ga


People also ask

How do I make an image grayscale in HTML?

In CSS, filter property is used to convert an image into grayscale image. Filter property is mainly used to set the visual effect of an image. Example 1: In this example, use filter: grayscale(100%) to convert an image into grayscale.

How do I make a color image grayscale?

Change a picture to grayscale or to black-and-whiteRight-click the picture that you want to change, and then click Format Picture on the shortcut menu. Click the Picture tab. Under Image control, in the Color list, click Grayscale or Black and White.

How do I grayscale an image code?

I = rgb2gray( RGB ) converts the truecolor image RGB to the grayscale image I . The rgb2gray function converts RGB images to grayscale by eliminating the hue and saturation information while retaining the luminance.

How do I make an image black in HTML?

0% will make the image completely black. 100% (1) is default and represents the original image.


1 Answers

Alpha is "not a color". You should copy it as it is, leaving the transparent part transparent. Just remove the line:

px[i+3] = greyScale;
like image 84
opalenzuela Avatar answered Sep 30 '22 19:09

opalenzuela