java如何处理灰度图片_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);

}

}

处理前:

0818b9ca8b590ca3270a3433284dd417.png

处理后:

0818b9ca8b590ca3270a3433284dd417.png

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值