Header Ads

How To Convert A Picture to GrayScale Image In Java

Objective:
In this post we will check out how to convert a normal jpg image to Gray scale.
Or else in a simple word this post talks about how to convert a color image to black and white.
Approach:
The approach will be to calculate the pixel value.
Every image can be decomposed to pixels.say its width is 400 and height is 500. So this can be decomposed to 400X500 pixels. This is nothing but to decompose the picture into matrix structures.


Now, get the basic color of the intersection points like the red,green and blue color value.

If we get the RGB value for a color value as
R=120
G=80
B=240

Now we need to calculate the average value for this position.
Avg value=(120+80+240)/3~107
Now we can set the RGB value as 107,107,107 for this position.

Code Snippet:
How to get the image-
// Save the image file as a BufferedImage object
BufferedImage pic = ImageIO.read(new File("E:\\finance.jpg")); 
Now decompose the image into pixels
// Loop through all the pixels in the image (w = width, h = height)
  for(int w = 0; w < pic.getWidth() ; w++)
  {
   for(int h = 0 ; h < pic.getHeight() ; h++)
   {
}
}
How to calculate the average color value
    
// use the RGB values to get their average.
int averageColorval = ((color.getRed() + color.getGreen() + color.getBlue())/3); 
Real Implementation:
Let us see how the real implementation goes:
import java.awt.Color;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;

public class jpgtogray 
{
  public static void main(String[] args) throws IOException 
 {
// Save the image file as a BufferedImage object
BufferedImage pic = ImageIO.read(new File("E:\\finance.jpg"));
// Loop through all the pixels in the image (w = width, h = height)
for(int w = 0; w < pic.getWidth() ; w++)
{
  for(int h = 0 ; h < pic.getHeight() ; h++)
  {
// BufferedImage.getRGB() saves the colour of the pixel as a single integer.
// use Color(int) to grab the RGB values individually.
Color color = new Color(pic.getRGB(w, h));
// use the RGB values to get their average.
int averageColorval = ((color.getRed() + color.getGreen() + color.getBlue())/3);
// create a new Color object using the average colour as the red, green and blue
// colour values
Color avg = new Color(averageColorval, averageColorval, averageColorval);
// set the pixel at that position to the new Color object using Color.getRGB().
pic.setRGB(w, h, avg.getRGB());
   }
}
// save the newly created image in a new file.
ImageIO.write(pic, "jpg", new File("E:\\finance.jpg"));
}
} 
Output:
I tried to change the picture by providing the left side picture as input and the program gave output which is there in the right side.

Please let me know if you like this post. The concept is taken from here and  here. If you like the post let me know how do you find this program.
Powered by Blogger.