Java: extract Alpha Channel from BufferedImage

断了今生、忘了曾经 提交于 2019-12-01 05:15:43

问题


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)


回答1:


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));
}



回答2:


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; 



回答3:


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?



来源:https://stackoverflow.com/questions/6176560/java-extract-alpha-channel-from-bufferedimage

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!