Our Feeds

Sunday 19 February 2017

AJITH KP

Easiest way to convert RGB Color Image to Gray scale Image in Java

Hello GuyZ,
     I would like to share Java code to convert RGB images to Gray scale images. I have seen many Java codes which converts image to Gray scale by decomposing each pixel value to red, green and blue values. Then calculate (R+G+B)/3 and set this value to corresponding pixel.
     But I would like to share simplest code to convert color images to gray scale without calculations. The method I'm following is creating an Raster object, I'm using WritableRaster - because it allows reading and writing pixel values. Here I'm creating two WritableRaster objects - one for source image reading, second for writing pixels in output file.

WritableRaster wr = src.getRaster();
WritableRaster gr = gImg.getRaster();

Then using loop, read all pixels from source image and write it to output file. To read pixels, I used getSample(i, j, 0) function of WritableRaster, where i - column number, j - row number of pixel and 0 to get gray scale value for that pixel. After read gray scale value, set this value for output WritableRaster by using function, setSample(i, j, 0, gray_value). The gray_value is the value returned by getSample() function.
RGB Color image to Gray scale conversion Java
before converting to gray scale image
RGB Color image to Gray scale conversion Java
After converting to gray scale

Java Source Code

import java.awt.image.BufferedImage;
import java.awt.image.WritableRaster;
import java.io.File;
import javax.imageio.ImageIO;

/*
(C) AJITH KP (C) : TERMINALCODERS
*/

public class GrayscaleConversion {
    public static void main(String[] args) {
        System.out.println("#! TERMINALCODERS ::..\nhttp://www.terminalcoders.blogspot.com");
        if(args.length<2){
            System.out.println("Usage: java GrayscaleConversion <input file name> <output file name>");
        }
        else{
            try{
                File in = new File(args[0]);
                File out = new File(args[1]);
                BufferedImage img = ImageIO.read(in);
                BufferedImage gray = getGrayscaleImage(img);
                ImageIO.write(gray, "png", out);
                System.out.println("Grayscale image is saved in file: "+args[1]);
            } catch(Exception e){
                System.out.println(e);
            }
        }
    }

    private static BufferedImage getGrayscaleImage(BufferedImage src) {
        BufferedImage gImg = new BufferedImage(src.getWidth(), src.getHeight(), BufferedImage.TYPE_BYTE_GRAY);
        WritableRaster wr = src.getRaster();
        WritableRaster gr = gImg.getRaster();
        for(int i=0;i<wr.getWidth();i++){
            for(int j=0;j<wr.getHeight();j++){
                gr.setSample(i, j, 0, wr.getSample(i, j, 0));
            }
        }
        gImg.setData(gr);
        return gImg;
    }
    
}