package cc.mrbird.febs.mall.test;
|
|
import javax.imageio.ImageIO;
|
import java.awt.*;
|
import java.awt.image.BufferedImage;
|
import java.awt.image.RenderedImage;
|
import java.io.File;
|
import java.io.IOException;
|
|
public class getGray {
|
|
/**
|
* 将输入的图片转换成灰度图片
|
* @param bufferedImage_start
|
* @return
|
*/
|
public static BufferedImage gray(BufferedImage bufferedImage_start){ //定义灰度方法 返回值为BufferedImage对象
|
int width = bufferedImage_start.getWidth();
|
int height =bufferedImage_start.getHeight();
|
BufferedImage bufferedImage_end = new BufferedImage(width,height, BufferedImage.TYPE_3BYTE_BGR ); //构建新的对象模型
|
// 遍历图片的RGB值,把得到的灰度值存到bufferedImage_end中,然后返回bufferedImage_end
|
for (int y = 0; y < height; y++) {
|
for (int x = 0; x < width; x++) {
|
|
int pixel = bufferedImage_start.getRGB(x, y);
|
int[] rgb = new int[3]; //分别表示红绿蓝RGB。
|
rgb[0] = pixel >> 16 & 0xff;
|
rgb[1] = pixel >> 8 & 0xff;
|
rgb[2] = pixel & 0xff;
|
int gray = (rgb[0] * 28 + rgb[1] * 151 + rgb[2] * 77) >> 8;
|
|
// Color color = new Color(bufferedImage_start.getRGB(x,y));//构建Color获取图片像素点
|
// int gray = (int)(color.getRed() * 0.2126 + color.getGreen() * 0.7152 + color.getBlue() * 0.0722);
|
Color color_end = new Color(gray,gray,gray); //将设置的像素设置到bufferedImage_end
|
bufferedImage_end.setRGB(x,y,color_end.getRGB());
|
}
|
}
|
return bufferedImage_end;
|
}
|
|
public static void main(String[] args) {
|
try{
|
RenderedImage rendImage =gray(ImageIO.read(new File("D:\\image\\inputDpi.png")));
|
File file = new File("D:\\image\\outDpi.png");
|
ImageIO.write(rendImage, "png", file);
|
}catch(IOException e){
|
System.out.println(e);
|
}
|
}
|
|
}
|