In this set we will be converting a colored image to negative image.Note: In a negative image the Alpha component of the image will be same as the original image, but the RGB will be changed i.e, all three RGB components will be having a value of 255-original component value.

Algorithm:

Get the RGB value of the pixel.

Calculate new RGB values as follows:

R = 255 – R

G = 255 – G

B = 255 – B

Replace the R, G and B value of the pixel with the values calculated in step 2.

Repeat Step 1 to Step 3 for each pixels of the image.

Implementation of the above algorithm:

// Java program to demonstrate colored to negative conversion

importjava.io.File;

importjava.io.IOException;

importjava.awt.image.BufferedImage;

importjavax.imageio.ImageIO;

publicclassNegative

{

publicstaticvoidmain(String args[])throwsIOException

{

BufferedImage img = null;

File f = null;

// read image

try

{

f = newFile("G:\\Inp.jpg");

img = ImageIO.read(f);

}

catch(IOException e)

{

System.out.println(e);

}

// Get image width and height

intwidth = img.getWidth();

intheight = img.getHeight();

// Convert to negative

for(inty = 0; y < height; y++)

{

for(intx = 0; x < width; x++)

{

intp = img.getRGB(x,y);

inta = (p>>24)&0xff;

intr = (p>>16)&0xff;

intg = (p>>8)&0xff;

intb = p&0xff;

//subtract RGB from 255

r = 255- r;

g = 255- g;

b = 255- b;

//set new RGB value

p = (a<<24) | (r<<16) | (g<<8) | b;

img.setRGB(x, y, p);

}

}

// write image

try

{

f = newFile("G:\\Out.jpg");

ImageIO.write(img, "jpg", f);

}

catch(IOException e)

{

System.out.println(e);

}

}

}

Note : This code will not run on online IDE as it needs an image on disk.

Inp.jpg
Out.jpg

This article is contributed by Pratik Agarwal. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.