Java Graphics How to - Convert negative image to positive








Question

We would like to know how to convert negative image to positive.

Answer

import java.awt.Color;
import java.awt.image.BufferedImage;
import java.io.File;
import java.net.URL;
// w w  w.  j  a  v a 2s  .c om
import javax.imageio.ImageIO;

public class Main {
  public static void main(String[] args) throws Exception {
    BufferedImage inputFile = ImageIO.read(new URL("http://www.java2s.com/style/download.png"));

    for (int x = 0; x < inputFile.getWidth(); x++) {
      for (int y = 0; y < inputFile.getHeight(); y++) {
        int rgba = inputFile.getRGB(x, y);
        Color col = new Color(rgba, true);
        col = new Color(255 - col.getRed(), 255 - col.getGreen(),
            255 - col.getBlue());
        inputFile.setRGB(x, y, col.getRGB());
      }
    }

    File outputFile = new File("invert.png");
    ImageIO.write(inputFile, "png", outputFile);

  }
}