Convert Image to Grayscale using Java
In this example we demonstrate how to convert Image to Grayscale using Java.
Convert Image to Grayscale
We use the ImageIO.read()
method to read an image to BufferedImage
. Then we loop over each pixel and calculate the RGB
grayscale colors and adjust it using the setRGB()
method, passing in the dimensions and color of each pixel.
package com.memorynotfound.image;
import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
public class ConvertGrayScale {
public static void main(String... args) {
try {
File input = new File("/tmp/duke.png");
BufferedImage image = ImageIO.read(input);
BufferedImage result = new BufferedImage(
image.getWidth(),
image.getHeight(),
BufferedImage.TYPE_INT_RGB);
Graphics2D graphic = result.createGraphics();
graphic.drawImage(image, 0, 0, Color.WHITE, null);
for (int i = 0; i < result.getHeight(); i++) {
for (int j = 0; j < result.getWidth(); j++) {
Color c = new Color(result.getRGB(j, i));
int red = (int) (c.getRed() * 0.299);
int green = (int) (c.getGreen() * 0.587);
int blue = (int) (c.getBlue() * 0.114);
Color newColor = new Color(
red + green + blue,
red + green + blue,
red + green + blue);
result.setRGB(j, i, newColor.getRGB());
}
}
File output = new File("/tmp/duke-grayscale.png");
ImageIO.write(result, "png", output);
} catch (IOException e) {
e.printStackTrace();
}
}
}
Converted Images
To demonstrate the result, we added the following table. You can see that the original image on the left is converted to grayscale on the right.
duke.png (original) | duke-grayscale.png |
---|---|
Background: transparent | Background: white |
Size: 9KB | Size: 14KB |