Java – Convert color images to grayscale images in Java

Convert color images to grayscale images in Java… here is a solution to the problem.

Convert color images to grayscale images in Java

I want to convert a color image to grayscale without too many predefined methods.

The code to read the color image is here

Main method:

BufferedImage img = null;
try {
    img = ImageIO.read(new File(IMG));

int[][] pixelData = new int[img.getHeight() * img.getWidth()][3];
    int[] rgb;

int counter = 0;
    for (int i = 0; i < img.getWidth(); i++) {
        for (int j = 0; j < img.getHeight(); j++) {
            rgb = getPixelData(img, i, j);

for (int k = 0; k < rgb.length; k++) {
                pixelData[counter][k] = rgb[k];
            }
            counter++;
        }
    }
} catch (IOException e) {
    e.printStackTrace();
}

Another method:

private static int[] getPixelData(BufferedImage img, int x, int y) {
    int argb = img.getRGB(x, y);
    int rgb[] = new int[] {
        (argb >> 16) & 0xff, //red
        (argb >>  8) & 0xff, //green
        (argb      ) & 0xff  //blue
    };

System.out.println("rgb: " + rgb[0] + " " + rgb[1] + " " + rgb[2]);
    return rgb;
}

I need to convert output to grayscale… Here are some outputs

 rgb: 255 255 255
 rgb: 255 255 255
 rgb: 255 255 255
 rgb: 255 255 255
 rgb: 255 255 255
 rgb: 255 255 255

I need to check the RGB of each pixel and convert it to grayscale.

Solution

The quick and dirty way is:

    int avg = (( rgb[0] + rgb[1] + rgb[2]) / 3);

int grey_rgb = 0;
    for(int i = 0; i < 4; i++) {
        grey_rgb <<= 8;
        grey_rgb |= avg & 0xFF;
    }

img.setRGB(x, y, grey_rgb );

A nuance of gray is obtained when all its RGB components contain the same value, such as 240 240 240. To achieve this, we only need the average of the numeric representation of the RGB component of the color.

For more advanced algorithms, see: tannerhelland.com/3643/grayscale-image-algorithm-vb6.

Related Problems and Solutions