Search code examples
javacanvasjavafxcolors

What is the best way to read pixels of a JavaFX Canvas?


I want to get the color for specific coordinates inside a Canvas. I already tried getting a snapshot using this code:

WritableImage snap = gc.getCanvas().snapshot(null, null);
snap.getPixelReader().getArgb(x, y); //This just gets the color without assigning it.

But it just takes too much time for my application. I was wondering if there is any other way to access the color of a pixel for which I know the coordinates.


Solution

  • A Canvas buffers the drawing instructions prescribed by invoking the methods of a GraphicsContext. There are no pixels to read until the Canvas is rendered in a later pulse, and the internal format of the instruction buffer is not exposed in the API.

    If a snapshot() of the Canvas is feasible, a rendered pixel may be examined using the resulting image's PixelReader.

    int aRGB = image.getPixelReader().getArgb(x, y);
    

    This example focuses on a single pixel. This example displays the ARGB BlendMode result in a TextField and a Tooltip as the mouse moves on the Canvas. More examples may be found here.

    As an alternative, consider drawing into a BufferedImage, illustrated here, which allows access to the image's pixels directly and via its WritableRaster. Adding the following line to this complete example outputs the expected value for opaque red in ARGB order: ffff0000.

    System.out.println(Integer.toHexString(bi.getRGB(50, 550)));
    

    image