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 it. I just know how to get a 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 this 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; } 
+4
source share
2 answers

Use Java2D ColorConvertOp.filter (..) to convert BufferedImage colors with the 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); 
+7
source

Source: https://habr.com/ru/post/1399042/


All Articles