Get RGB of a BufferedImage

二次信任 提交于 2019-11-27 20:10:07

You get negative numbers since the int value you get from one of the pixels are composed by red, green, blue and alpha. You need to split the colors to get a value for each color component.

The simplest way to do this is to create a Color object and use the getRed, getGreen and getBlue (aswell as getAlpha) methods to get the components:

public static void main(String... args) throws Exception {

    BufferedImage image = ImageIO.read(
         new URL("http://upload.wikimedia.org/wikipedia/en/2/24/Lenna.png"));

    int w = image.getWidth();
    int h = image.getHeight();

    int[] dataBuffInt = image.getRGB(0, 0, w, h, null, 0, w); 

    Color c = new Color(dataBuffInt[100]);

    System.out.println(c.getRed());   // = (dataBuffInt[100] >> 16) & 0xFF
    System.out.println(c.getGreen()); // = (dataBuffInt[100] >> 8)  & 0xFF
    System.out.println(c.getBlue());  // = (dataBuffInt[100] >> 0)  & 0xFF
    System.out.println(c.getAlpha()); // = (dataBuffInt[100] >> 24) & 0xFF
}

Outputs:

173
73
82
255
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!