Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java: extract Alpha Channel from BufferedImage

Tags:

java

alpha

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)

like image 558
clamp Avatar asked Dec 17 '22 13:12

clamp


1 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));
}
like image 95
vbence Avatar answered Jan 03 '23 10:01

vbence