user1209555
user1209555

Reputation: 47

How to convert an image from color to black and white (grayscale) in Java

I just want to convert this color image to black and white but I don't know how to do this. I just know how to get pixel. Can you help me?

    private BufferedImage image;
    private int[][]rgbValue;       

    public void setRgbValue(BufferedImage image){
        int width = image.getWidth();
        int height = image.getHeight();

        rgbValue = new int[width*height][3];
        int counter = 0;
        for(int i=0 ; i<width ; i++){
            for(int j=0 ; j<height ; j++){
                int color = image.getRGB(i, j);
                int red = (color & 0x00ff0000) >> 16;
                int green = (color & 0x0000ff00) >> 8;
                int blue = (color & 0x000000ff);
                rgbValue[counter][0] = red;
                rgbValue[counter][1] = green;
                rgbValue[counter][2] = blue;
                counter++;           
            }        
        }
    }

How do I combine that with this code?

  temp = red;
  red = green;
  green = blue;
  blue = temp;
  temp = 0;
  rgb[i] = ((red << 16)) + ((green << 8 )) + (blue );
  if(rgb[i] <= 0x670000){
      rgb[i] = 0x000000;
  } else { 
      rgb[i] = 0xffffff;
  }    

Upvotes: 4

Views: 8382

Answers (2)

d1e
d1e

Reputation: 6442

Use Java2D ColorConvertOp.filter(..) to convert colors of BufferedImage with specified ColorSpace.

BufferedImage bi = null; //Your BufferedImage goes here. null for compiler
ColorConvertOp op = 
    new ColorConvertOp(ColorSpace.getInstance(ColorSpace.CS_GRAY), null);
op.filter(bi, bi);

Upvotes: 7

Vince P
Vince P

Reputation: 1791

Have a look at this: http://spyrestudios.com/html5-canvas-image-effects-black-white/

Upvotes: 0

Related Questions