package new_world1;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.*;
import javax.imageio.ImageIO;
public class GrayScale {
BufferedImage image;
int width;
int height;//定义变量
public GrayScale() { //构造方法
try {
File input = new File("/Users/spurs/Desktop/bigsize.jpg");//输入地址
image = ImageIO.read(input);
width = image.getWidth();
height = image.getHeight();
System.out.println("width, height: " + width + "," + height);//显示生成图片尺寸
for(int i=0; i<height; i++){
for(int j=0; j<width; j++){
Color c = new Color(image.getRGB(j, i));
int red = (int)(c.getRed() * 0.299);
int green = (int)(c.getGreen() * 0.587);
int blue = (int)(c.getBlue() *0.114);//R,G,B,对应亮度
Color newColor = new Color(red+green+blue,
red+green+blue,red+green+blue);
image.setRGB(j,i,newColor.getRGB()); //调用setRGB方法
}
}
File ouptut = new File("/Users/spurs/Desktop/bigsize_exchange.jpg");//输出地址
ImageIO.write(image, "jpg", ouptut);
} catch (Exception e) {
System.out.println("the exception is:");//捕获IO异常
}
}
static public void main(String args[]) throws Exception
{
GrayScale obj = new GrayScale();
}
}
效果: