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 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 = 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.