mafioso mafioso - 1 month ago 5x
Java Question

RGB image filter in java

I want to look my pictures like that:

enter image description here

I want to filter the image by pressing a button.

Currently, I have a

and I don't know how to set the pixels.

This converts my picture into the blue one but I don't know why and how can I set green and red?

int width = img.getWidth();
int height = img.getHeight();

for(int y = 0; y < height; y++){
for(int x = 0; x < width; x++){
int p = img.getRGB(x,y);

int r = (p>>16)&0xff;
int g = (p>>8)&0xff;
int b = p & 0xff;

this.lblFilteredImage.setIcon(new ImageIcon(img));


You can easily seperate the red, green and blue values through the java.awt.Color class, which takes the color value from img.getRGB(x,y) as a constructor Argument:

Color color = new Color(img.getRGB(x,y));

int red = color.getRed();
int green = color.getGreen();
int blue = color.getBlue();

Now you can convert them back into the values needed for img.setRGB() through another java.awt.Color Object, which can also take red, green, and blue values in the constructor Color(red, green, blue) and has the method .getRGB() to get the full color code back:

int onlyRed = new Color(red, 0, 0).getRGB();
int onlyGreen = new Color(0, green, 0).getRGB();
int onlyBlue = new Color(0, 0, blue).getRGB();

Now to get a completely red image you just have to write img.setRGB(x, y, onlyRed);.