Convert GrayScale Image using Java

Hello everyone, here I have attached Simple program about How to Convert GrayScale Image using Java. The program has been tested and output is shared in the same post.

GrayScaleConversion.java

package com.javatraineronline;

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

import javax.imageio.ImageIO;

public class GrayScaleConversion {

	private BufferedImage image;
	private int width;
	private int height;
	
	private final String FILE_FORMAT = "jpg";
	
	private final double VAL_1 = 0.220;
	private final double VAL_2 = 0.550;
	private final double VAL_3 = 0.120;

	// Converting Image to GrayScale
	public void convertGrayScale(String outputImageName) {

		try {

			if (outputImageName != null && !"".equals(outputImageName)) {

				for (int i = 0; i < height; i++) {

					for (int j = 0; j < width; j++) {

						Color c = new Color(image.getRGB(j, i));
						
						int red = (int) (c.getRed() * VAL_1);
						int green = (int) (c.getGreen() * VAL_2);
						int blue = (int) (c.getBlue() * VAL_3);
						
						Color newColor = new Color(red + green + blue,

						red + green + blue, red + green + blue);

						image.setRGB(j, i, newColor.getRGB()); // Setting the new RGB Color
					}
				}

				// Defining the Output File Object
				File ouptut = new File(outputImageName);
				
				// Writing the Output Image to File System
				ImageIO.write(image, FILE_FORMAT, ouptut);
			} else {

				System.out.println("Please provide the valid file name!!!");
			}
		} catch (Exception ex) {

			System.out.println(ex.getMessage());
			ex.printStackTrace();
		}

	}

	public GrayScaleConversion(String inputImageName) {

		try {

			if (inputImageName != null && !"".equals(inputImageName)) {

				File input = new File(inputImageName);
				image = ImageIO.read(input);
				width = image.getWidth();
				height = image.getHeight();

			} else {

				System.out.println("Please provide the vaild file name!!!");
			}

		} catch (Exception ex) {

			System.out.println(ex.getMessage());
			ex.printStackTrace();
		}
	}

	static public void main(String args[]) throws Exception {
		GrayScaleConversion obj = new GrayScaleConversion("C:\\dineshkrishnan\\java.jpg");
		
		obj.convertGrayScale("C:\\dineshkrishnan\\gray_java.jpg");
		
	}
}

Output

Convert GrayScale Image using Java