How to Invert the color of an image using JavaFX?

JavaFX provides two interface namely PixelReader and PixelWriter in the javafx.scene.image. Using the methods provided by them you can read and write the contents of an image such as pixels, color values, etc.

You can get the objects of these interfaces using the getPixelReader() and getPixelWriter() methods respectively.

To invert an image −

  • Create an InputStream object by passing the URL(String) of the required image.

  • Instantiate the Image class bypassing the above-created input stream object as a parameter.

  • Get the PixelReader and PixelWriter objects of the loaded image using the respective methods.

  • Read each color value of the image using the getColor() method of the ImageReader class.

  • Invert each color value using the invert() method of the javafx.scene.paint.Color class.

  • Set the inverted color values to the image using the setColor() method of the ImageWriter class.

  • Finally, display the resultant image using the ImageView.


Following JavaFX program reads the pixels of an image, inverts the color values and displays the result −

import javafx.application.Application;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.image.PixelReader;
import javafx.scene.image.PixelWriter;
import javafx.scene.image.WritableImage;
import javafx.scene.paint.Color;
import javafx.stage.Stage;
public class ReadingWritingPixels extends Application {
   public void start(Stage stage) throws IOException {
      //creating the image object
      InputStream stream = new FileInputStream("D:\images\elephant.jpg");
      Image image = new Image(stream);
      //Reading the pixels
      PixelReader reader = image.getPixelReader();
      //Writing the read pixels
      int w = (int)image.getWidth();
      int h = (int)image.getHeight();
      WritableImage wImage = new WritableImage(w, h);      
      PixelWriter writer = wImage.getPixelWriter();
      //Reading the color of the image
      for(int y = 0; y < h; y++) {
         for(int x = 0; x < w; x++) {
            //Retrieving the color of the pixel of the loaded image
            Color color = reader.getColor(x, y);
            //Setting the color to the writable image
            writer.setColor(x, y, color.invert());
      //Creating the image view
      ImageView imageView = new ImageView();
      //Setting image to the image view
      //Setting the image view parameters
      //Setting the Scene object
      Group root = new Group(imageView);
      Scene scene = new Scene(root, 595, 370, Color.BEIGE);
      stage.setTitle("Reading/Writing Pixels");
   public static void main(String args[]) {