I would like to extract the Alpha Channel from a bufferedimage and paint it in a separate image using greyscale. (like it is displayed in photoshop)
3 Answers
Not tested but contains the main points.
public Image alpha2gray(BufferedImage src) {
if (src.getType() != BufferedImage.TYPE_INT_ARGB)
throw new RuntimeException("Wrong image type.");
int w = src.getWidth();
int h = src.getHeight();
int[] srcBuffer = src.getData().getPixels(0, 0, w, h, (int[]) null);
int[] dstBuffer = new int[w * h];
for (int i=0; i<w*h; i++) {
int a = (srcBuffer[i] >> 24) & 0xff;
dstBuffer[i] = a | a << 8 | a << 16;
}
return Toolkit.getDefaultToolkit().createImage(new MemoryImageSource(w, h, pix, 0, w));
}

- 20,084
- 9
- 69
- 118
-
I think the shifts in the assignment need to go the other way? `a | a << 8 | a << 16` – Austin Hyde Mar 31 '15 at 17:56
-
This does not compile. Line to fix: `int[] srcBuffer = src.getData().getPixels(0, 0, w, h, (int[]) null);` – Stefan Reich Feb 21 '17 at 18:08
-
@vbence I didn't know I could edit it, thanks. I see you edited it yourself – Stefan Reich Feb 24 '17 at 16:24
I don't believe there's a single method call to do this; you would have to get all the image data and mask off the alpha byte for each pixel. So for example, use getRGB()
to get the ARGB pixels for the image. The most significant byte is the alpha value. So for each pixel in the array you get from getRGB()
,
int alpha = (pixel >> 24) & 0xFF;

- 80,601
- 10
- 150
- 186
-
-
I think this is possible without manually looping over the pixels which might result in better performance on some platforms, see my answer. – Waldheinz May 30 '11 at 13:11
You could grab the Raster from the BufferedImage, and then create a child Raster of this one which contains only the band you're interested in (the bandList
parameter). From this child raster you can create a new BufferedImage with a suitable ColorModel
which would only contain the grayscale aplpha mask.
The benefit of doing it this way instead of manually iterating over the pixels is that the runtime has chance to get an idea of what you are doing, and thus this might get accelerated by exploiting the hardware capabilities. Honestly I doubt it will be accelerated with current JVMs, but who knows what the future brings?

- 10,399
- 3
- 31
- 61