3

By calling getRGB(int x, int y) with a BufferedImage object, one gets a single, negative number.

How can I convert three different values (a red, a green, and a blue) into this single, negative number?

Dylan Wheeler
  • 6,928
  • 14
  • 56
  • 80
  • btw. every BufferedImage contains an array that holds all the pixels. If the BufferedImage is of type TYPE_INT_RGB that array will be an int array. So if you want to do a lot of pixel manipulation you can speed up your program by writing directly to that array. You can get it with int[] pixels = ((DataBufferInt)image.getRaster().getDataBuffer()).getData() – Tesseract Dec 02 '12 at 01:56
  • 3
    Possible duplicate of [Java BufferedImage getting red, green and blue individually](https://stackoverflow.com/questions/2615522/java-bufferedimage-getting-red-green-and-blue-individually) – Michu93 Jan 25 '19 at 12:47
  • @Michu93 This question asks the reverse of that, so this isn't a duplicate – Mark Rotteveel Jan 25 '19 at 16:10

3 Answers3

10

Using the Color class:

new Color(r, g, b).getRGB()
JB Nizet
  • 678,734
  • 91
  • 1,224
  • 1,255
3

BufferedImage ends up delegating to java.awt.image.ColorModel which uses the following code:

public int getRGB(Object inData) {
    return (getAlpha(inData) << 24)
        | (getRed(inData) << 16)
        | (getGreen(inData) << 8)
        | (getBlue(inData) << 0);
}

Modifying this to suit your needs is a trivial exercise.

corsiKa
  • 81,495
  • 25
  • 153
  • 204
-1

JB Nizet's answer is great, but it can be really slow when creating new objects of type 'Color' thousands of times. The simplest way would be:

int rgb = (red << 16 | green << 8 | blue)

As answered by ByteBit

Community
  • 1
  • 1
Zar E Ahmer
  • 33,936
  • 20
  • 234
  • 300