Image Processing in Java | Set 3 (Colored image to greyscale image conversion)

We strongly recommend to refer below post as a prerequisite of this.

In this set we will be converting a coloured image to greyscale image.
Note(Think intuitively): In a greyscale image the Alpha component of the image will be same as the original image, but the RGB wil be changed i.e, all three RGB components will be having a same value for each pixels.


  1. Get the RGB value of the pixel.
  2. Find the average of RGB i.e., Avg = (R+G+B)/3
  3. Replace the R, G and B value of the pixel with average (Avg) calculated in step 2.
  4. Repeat Step 1 to Step 3 for each pixels of the image.

Implementation of the above algorithm:

// Java program to demonstrate colored to greyscale conversion
import java.io.File;
import java.io.IOException;
import java.awt.image.BufferedImage;
import javax.imageio.ImageIO;
public class Grayscale
    public static void main(String args[])throws IOException
        BufferedImage img = null;
        File f = null;
        // read image
            f = new File("G:\Inp.jpg");
            img = ImageIO.read(f);
        catch(IOException e)
        // get image's width and height
        int width = img.getWidth();
        int height = img.getHeight();
        // convert to greyscale
        for (int y = 0; y < height; y++)
            for (int x = 0; x < width; x++)
                // Here (x,y)denotes the coordinate of image 
                // for modifying the pixel value.
                int p = img.getRGB(x,y);
                int a = (p>>24)&0xff;
                int r = (p>>16)&0xff;
                int g = (p>>8)&0xff;
                int b = p&0xff;
                // calculate average
                int avg = (r+g+b)/3;
                // replace RGB value with avg
                p = (a<<24) | (avg<<16) | (avg<<8) | avg;
                img.setRGB(x, y, p);
        // write image
            f = new File("G:\Out.jpg");
            ImageIO.write(img, "jpg", f);
        catch(IOException e)

Note : This code will not run on online IDE as it needs an image on disk.


In the next set we will be learning how to convert a colored image to negative image in JAVA.

Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.

This article is attributed to GeeksforGeeks.org

You Might Also Like

leave a comment



load comments

Subscribe to Our Newsletter