public static BufferedImage toGrayScale(BufferedImage image) { BufferedImage result = new BufferedImage(image.getWidth(), image.getHeight(), BufferedImage.TYPE_BYTE_GRAY); Raster raster = image.getData(); WritableRaster grayRaster = result.getRaster(); int height = raster.getHeight(); int sample = 0; for (int x = 0; x < raster.getWidth(); ++x) { for (int y = 0; y < height; ++y) { sample = raster.getSample(x, y, 0) + raster.getSample(x, y, 1) + raster.getSample(x, y, 2); grayRaster.setSample(x, y, 0, (int) ((float) sample / 3.0)); } } return result; }
// returns a value specifying some kind of average brightness in the image. protected int getAverageBrightness(BufferedImage img) { Raster r = img.getData(); int total = 0; for (int y = 0; y < r.getHeight(); y++) { for (int x = 0; x < r.getWidth(); x++) { total += r.getSample(r.getMinX() + x, r.getMinY() + y, 0); } } return (int) (total / ((r.getWidth() / factorD) * (r.getHeight() / factorD))); }