public class PictureTest {
/**
* 几种灰度化的方法
分量法:使用RGB三个分量中的一个作为灰度图的灰度值。
最值法:使用RGB三个分量中最大值或最小值作为灰度图的灰度值。
均值法:使用RGB三个分量的平均值作为灰度图的灰度值。
加权法:由于人眼颜色敏感度不同,按下一定的权值对RGB三分量进行加权平均能得到较合理的灰度图像。
一般情况按照:Y = 0.30R + 0.59G + 0.11B。
*/
public static void main(String[] args) throws IOException {
BufferedImage bufferedImage = ImageIO.read(new File(System.getProperty("user.dir") + "/test.jpg"));
BufferedImage grayImage = new BufferedImage(bufferedImage.getWidth(), bufferedImage.getHeight(), bufferedImage.getType());
for (int i = 0; i < bufferedImage.getWidth(); i++) {
for (int j = 0; j < bufferedImage.getHeight(); j++) {
final int color = bufferedImage.getRGB(i, j);
final int r = (color >> 16) & 0xff;
final int g = (color >> 8) & 0xff;
final int b = color & 0xff;
int gray = (int) (0.3 * r + 0.59 * g + 0.11 * b);
System.out.println(i + " : " + j + " " + gray);
int newPixel = colorToRGB(255, gray, gray, gray);
grayImage.setRGB(i, j, newPixel);
}
}
File newFile = new File(System.getProperty("user.dir") + "/ok.jpg");
ImageIO.write(grayImage, "jpg", newFile);
}
private static int colorToRGB(int alpha, int red, int green, int blue) {
int newPixel = 0;
newPixel += alpha;
newPixel = newPixel << 8;
newPixel += red;
newPixel = newPixel << 8;
newPixel += green;
newPixel = newPixel << 8;
newPixel += blue;
return newPixel;
}
}
转载于:https://my.oschina.net/u/2385255/blog/737686