java 实现彩色图片转成黑白图片

因业务需求,前段时间做了彩色图片转为黑白图片。以下代码作为参考:

public static void changeImge(File img) {
try {
Image image = ImageIO.read(img);
int srcH = image.getHeight(null);
int srcW = image.getWidth(null);
BufferedImage bufferedImage = new BufferedImage(srcW, srcH,BufferedImage.TYPE_3BYTE_BGR);
bufferedImage.getGraphics().drawImage(image, 0,0, srcW, srcH, null);
bufferedImage=new ColorConvertOp(ColorSpace.getInstance(ColorSpace.CS_GRAY),null).filter (bufferedImage,null);
FileOutputStream fos = new FileOutputStream(img);
JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(fos);
encoder.encode(bufferedImage);
fos.close();
} catch (IOException e) {
e.printStackTrace();
throw new IllegalStateException("图片转换出错!", e);
}
}