Java Graphics How to - Create a Grayscaled image








Question

We would like to know how to create a Grayscaled image.

Answer

import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
/*w  w  w. ja v  a 2 s  .  co m*/
import javax.imageio.ImageIO;

public class Main {
  public static void main(String[] args) throws IOException {

    int width = 100;// width of your image
    int height = 100; // height of your image

    BufferedImage img = new BufferedImage(width, height,
        BufferedImage.TYPE_INT_RGB);
    for (int x = 0; x < width; ++x) {
      for (int y = 0; y < height; ++y) {
        int grayscale = 123;
        int colorValue = grayscale | grayscale << 8 | grayscale << 16;
        img.setRGB(x, y, colorValue);
      }
    }
    ImageIO.write(img, "png", new File("c:/Java_Dev/output.png"));
  }
}