Converting a color Image to a grayscale image programatically using Java

Hi in the last couple of days i was working with one of my friend to create a website.We had a requirement in which, we should put lot of images that need to be converted as gray scale images from color, Then we had lot of work with photoshop to make every image into gray scale and then port into server which is little tedious job, then i have made this program which will work perfectly to make colored images into gray scale images and i looped it in the image list to get all images as gray scale on the fly. Thanks to Java API 🙂

The below code is self explanatory.

/**
*
*/
package com.spark.image.converter;

import java.awt.Color;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;

import javax.imageio.ImageIO;

/**
* @author Mantha Pavan Kumar
*
*/
public class Color2Grayscale {

/**
* @param args
* @throws IOException
*/
public static void main(String[] args) throws IOException {
// Save the image file as a BufferedImage object
BufferedImage cat = ImageIO.read(new File("image.JPG"));

// Loop through all the pixels in the image (w = width, h = height)
for (int w = 0; w < cat.getWidth(); w++) {
for (int h = 0; h < cat.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(cat.getRGB(w, h));

// use the RGB values to get their average.
int averageColor = ((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(averageColor, averageColor, averageColor);

// set the pixel at that position to the new Color object using
// Color.getRGB().
cat.setRGB(w, h, avg.getRGB());
}
}

// save the newly created image in a new file.
ImageIO.write(cat, "jpg", new File("image_greyscale.jpg"));
}

}

Happy Coding.

Advertisements

4 thoughts on “Converting a color Image to a grayscale image programatically using Java

    1. Hi Ashok r u an electronics engg if so can u please contact me i have very nice project in my view we can implement for our self satisfaction as a research 🙂 my email is:manthapavankumar@gmail.com

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s