如何在Java中将图像从彩色转换为黑白(灰度)

时间:2012-02-29 16:08:16

标签: java image

我只想将此彩色图像转换为黑白,但我不知道该怎么做。我只知道如何获得像素。你能救我吗?

    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++;           
            }        
        }
    }

如何将其与此代码结合使用?

  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;
  }    

2 个答案:

答案 0 :(得分:7)

使用Java2D ColorConvertOp.filter(..)将BufferedImage的颜色转换为指定的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);

答案 1 :(得分:0)