简体   繁体   中英

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

I have a PNG image like this:

在此处输入图像描述

how could the color be changed in JavaFX?

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:

样本输出

I really liked the solution of @MS 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;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM