Plot the negative of an image in Java

Today, we will learn how to plot the negative of an image in Java.

First of all, we have to know what do we mean by the negative of an image. So Negatives image means brighter pixels becomes darker and darker becomes brighter.

Please note that there can be multiple ways to solve a problem as per your understanding.

for this tutorial, we will take each pixel value of the input image and calculate the new pixel value using the following formula:

new pixel value = 255¬† –¬† r

where 255 is the maximum value of color range and r is the pixel value of the input image.

Plot the negative of an image: Java Code

Here is the Java program provided below. We put our input image and output image too for an example so that you can understand what will be the output of this program.

import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;

class Main
{
    public static void main(String[] args)
    {
        invertImage("img.jpeg");
    }

    public static void invertImage(String imageName) {
        BufferedImage inputFile = null;
        try {
            inputFile = ImageIO.read(new File(imageName));
        } catch (IOException e) {
            e.printStackTrace();
        }

        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());
            }
        }

        try {
            File outputFile = new File("invert-"+imageName);
            ImageIO.write(inputFile, "jpeg", outputFile);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

Output:

input image:

Java image processing input image

input image

output image:

Plot the negative of an image in Java

output image

Now you know how to convert an image into its negative form using java. If you have any doubts feel free to comment.

You may also read:

How to Convert An Image To Binary Data In Java

How to convert image to byte array in Java

Leave a Reply

Your email address will not be published. Required fields are marked *