How to change the color of a .png image in JavaFX?

Viewed 442

I have a PNG image like this:

enter image description here

how could the color be changed in JavaFX?

2 Answers

You can use a Lighting effect, here is an example:

Lighting lighting = new Lighting(new Light.Distant(45, 90, Color.RED));
ColorAdjust bright = new ColorAdjust(0, 1, 1, 1);
lighting.setContentInput(bright);
lighting.setSurfaceScale(0.0);

imageView.setEffect(lighting);

Output:

sample output

I really liked the solution of @M.S which uses Lighting. However if you want to generate a reusable Image to render multiple ImageView nodes, below is one possible solution.

Please note that the below solution is to change the color of entire image by keeping the transparent pixels. May be if you have a white background images, you can tweak the code accordingly.

public static Image blendColor(final Image sourceImage, final Color blendColor) {
    final double r = blendColor.getRed();
    final double g = blendColor.getGreen();
    final double b = blendColor.getBlue();
    final int w = (int) sourceImage.getWidth();
    final int h = (int) sourceImage.getHeight();
    final WritableImage outputImage = new WritableImage(w, h);
    final PixelWriter writer = outputImage.getPixelWriter();
    final PixelReader reader = sourceImage.getPixelReader();
    for (int y = 0; y < h; y++) {
        for (int x = 0; x < w; x++) {
            // Keeping the opacity of every pixel as it is.
            writer.setColor(x, y, new Color(r, g, b, reader.getColor(x, y).getOpacity()));
        }
    }
    return outputImage;
}
Related