java 圖片灰度化

http://liuyu314.github.io/java/2014/05/24/grayscale/java

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;

    }
}
相關文章
相關標籤/搜索