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);
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.
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.
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.
0% will make the image completely black. 100% (1) is default and represents the original image.
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;
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