/** * 圖片灰化(效果不行,不建議。聽說:搜索「Java實現灰度化」,十有八九都是一種方法) * * @param bufferedImage 待處理圖片 * @return * @throws Exception */ public static BufferedImage grayImage(BufferedImage bufferedImage) throws Exception { int width = bufferedImage.getWidth(); int height = bufferedImage.getHeight(); BufferedImage grayBufferedImage = new BufferedImage(width, height, BufferedImage.TYPE_BYTE_GRAY); for (int x = 0; x < width; x++) { for(int y = 0 ; y < height; y++) { grayBufferedImage.setRGB(x, y, bufferedImage.getRGB(x, j)); } } }
/** * 圖片灰化(參考:http://www.codeceo.com/article/java-image-gray.html) * * @param bufferedImage 待處理圖片 * @return * @throws Exception */ public static BufferedImage grayImage(BufferedImage bufferedImage) throws Exception { int width = bufferedImage.getWidth(); int height = bufferedImage.getHeight(); BufferedImage grayBufferedImage = new BufferedImage(width, height, BufferedImage.TYPE_BYTE_GRAY); for (int x = 0; x < width; x++) { for (int y = 0; y < height; y++) { // 計算灰度值 final int color = bufferedImage.getRGB(x, y); 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); int newPixel = colorToRGB(255, gray, gray, gray); grayBufferedImage.setRGB(x, y, newPixel); } } return grayBufferedImage; } /** * 顏色份量轉換爲RGB值 * * @param alpha * @param red * @param green * @param blue * @return */ 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; }
[1] 《多媒體技術教程》Ze-Nian Li,Mark S.Drew著,機械工業出版社。
[2] 百度百科:灰度值
[3] Java color image to grayscale conversion algorithm(s) html