### Java将BufferedImage的ColorSpace转换为CS_GRAY而不使用ConvertColorOp

``````public static BufferedImage getGrayBufferedImage(BufferedImage image) {
BufferedImageOp op = new ColorConvertOp(ColorSpace
.getInstance(ColorSpace.CS_GRAY), null);
BufferedImage sourceImgGray = op.filter(image, null);

return sourceImgGray;
}
``````

#### 2 个答案:

`ColorConvertOp.filter`有两个参数。第二个参数也是`BufferedImage`，它将是目的地。如果您将正确的`BufferedImage`传递给`filter`方法，则可以避免麻烦，从而创建新的`BufferedImage`

``````private static int grayscale(int rgb) {
int r = rgb >> 16 & 0xff;
int g = rgb >> 8  & 0xff;
int b = rgb       & 0xff;
int cmax = Math.max(Math.max(r, g),b);
return (rgb & 0xFF000000) | (cmax << 16) | (cmax << 8) | cmax;
}
public static BufferedImage grayscale(BufferedImage bi) {
BufferedImage bout = new BufferedImage(bi.getWidth(), bi.getHeight(), BufferedImage.TYPE_INT_ARGB);
int[] rgbArray = new int[bi.getWidth() * bi.getHeight()];
rgbArray = bi.getRGB(0, 0, bi.getWidth(), bi.getHeight(), rgbArray, 0, bi.getWidth());
for (int i = 0, q = rgbArray.length; i < q; i++) {
rgbArray[i] = grayscale(rgbArray[i]);
}
bout.setRGB(0, 0, bout.getWidth(), bout.getHeight(), rgbArray, 0, bout.getWidth());
return bout;
}
``````