java 图片灰度化

/**
 *  ━━━━━━神兽出没━━━━━━ 
 *   ┏┓   ┏┓ 
 *  ┏┛┻━━━┛┻┓ 
 *     ┃       ┃
 * 	  ┃   ━   ┃ 
 *     ┃ ┳┛ ┗┳    ┃ 
 *  ┃       ┃ 
 *  ┃   ┻   ┃ 
 *  ┃       ┃ 
 *  ┗━┓   ┏━┛Code is far away from bug with the animal protecting 
 *    ┃   ┃    神兽保佑,代码无bug 
 *    ┃   ┃ 
 *    ┃   ┗━━━┓ 
 *    ┃       ┣┓ 
 *    ┃       ┏┛ 
 *    ┗┓┓┏━┳┓┏┛ 
 *     ┃┫┫ ┃┫┫ 
 *     ┗┻┛ ┗┻┛ 
 * 
 * ━━━━━━感觉萌萌哒━━━━━━ 
 */
package gt.controller.Images;

import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;

import javax.imageio.ImageIO;

/**
 * 类名称:ImageDemo2.java
 * 类描述:
 * 作    者:why
 * 时    间:2017年3月17日
 */
public class ImageDemo2 {
	/**
	 * 加权法灰度化(效果较好)
	 * 图片灰化(参考: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 gray = (int) (0.21 * r + 0.71 * g + 0.07 * 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;
		
	}
	public static void main(String[] args) throws Exception {
		File file = new File("D:\\ocrpic\\sjh.png");
		BufferedImage image = ImageIO.read(file);
		File newFile = new File("D:\\ocrpic\\sjh1.png");
		ImageIO.write(grayImage(image), "png", newFile);
	}
}

处理前:

java 图片灰度化_第1张图片

处理后:

java 图片灰度化_第2张图片

你可能感兴趣的:(java图像处理,java,Java随笔,图片,图片处理,灰度化)