Flank
Flank

Reputation:

How to get RGB values of a pixel in JavaFX

I am getting started with JavaFX and basically what I am trying to implement is a Color Picker. At first, I thought of having a rectangle with a LinearGradient that goes through all primary/secondary colors.

Looks like what I want, but the problem is that I can not get the RGB values at a given coordinate(x,y) in this Node. I know you can do it through the fill property of any Shape IF it is a Color.

But Is there anyway to get the RGB values of anything inside a LinearGradient/Paint ?

Upvotes: 2

Views: 3633

Answers (2)

Refactor
Refactor

Reputation: 524

The ColorPicker JavaFX example starts with a png image that is loaded to an image that then populates the ImageView.

The question starts with a JavaFX Rectangle containing LinearGradient.

To get the rectangle contents into a buffered image, one can use the java.awt.Robot:

        var rectangle = new java.awt.Rectangle(x,y,width,height);
        var robot = new java.awt.Robot();
        var bufferedImage = robot.createScreenCapture(rectangle);   

where rectangle would be describe the coordinates of the JavaFX Rectangle containing the bits of interest.

The robot.createScreenCapture call has the gotcha that to do the screen capture, the screen has to be visible. There should be a better of way to populate the buffered image but I've not yet encountered it.

Upvotes: 0

schnaader
schnaader

Reputation: 49719

Does this ColorPicker JavaFX example help?

[...]

function colorAtLocation(x:Integer, y:Integer) : Color {
    var bimg = iv.image.bufferedImage;
    if (x < 0 or x >= bimg.getWidth() or y < 0 or y >= bimg.getHeight()) {
        return null;
    }
    var rgb = bimg.getRGB(x, y);
    var r = Bits.bitAnd(Bits.shiftRight(rgb, 16), 0xff);
    var g = Bits.bitAnd(Bits.shiftRight(rgb,  8), 0xff);
    var b = Bits.bitAnd(Bits.shiftRight(rgb,  0), 0xff);
    Color.rgb(r, g, b)
}

function updateSelectedColor(e:MouseEvent) {
    var rgb = colorAtLocation(e.x, e.y);
    if (rgb != null) {
        picker.selectedColor = rgb;
    }
}

[...]

Upvotes: 1

Related Questions