![](https://i-blog.csdnimg.cn/blog_migrate/11ab61846568f7310c1fec6b75306fcd.jpeg)
全栈工程师开发手册 (作者:栾鹏)
java将图片灰度化
测试代码
public static void main(String[] args) {
//文件与BufferedImage间的转换
BufferedImage bi=file2img("11.jpg"); //读取图片
BufferedImage bii=img_gray(bi);
img2file(bii,"jpg","111.jpg"); //生成图片
}
将图片灰度化的函数代码
public static BufferedImage img_gray(BufferedImage imgsrc) {
try {
//创建一个灰度模式的图片
BufferedImage back=new BufferedImage(imgsrc.getWidth(), imgsrc.getHeight(), BufferedImage.TYPE_BYTE_GRAY);
int width = imgsrc.getWidth();
int height = imgsrc.getHeight();
for (int j = 0; j < height; j++) {
for (int i = 0; i < width; i++) {
back.setRGB(i,j,imgsrc.getRGB(i, j));
}
}
return back;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
读取图片和生成图片的代码
//读取图片
public static BufferedImage file2img(String imgpath) {
try {
BufferedImage bufferedImage=ImageIO.read(new File(imgpath));
return bufferedImage;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
//保存图片,extent为格式,"jpg"、"png"等
public static void img2file(BufferedImage img,String extent,String newfile) {
try {
ImageIO.write(img, extent, new File(newfile));
} catch (Exception e) {
e.printStackTrace();
}
}