Java - get pixel array from image

后端 未结 7 1177
面向向阳花
面向向阳花 2020-11-22 03:52

I\'m looking for the fastest way to get pixel data (int the form int[][]) from a BufferedImage. My goal is to be able to address pixel (x, y) from

7条回答
  •  深忆病人
    2020-11-22 04:35

    I found Mota's answer gave me a 10 times speed increase - so thanks Mota.

    I've wrapped up the code in a convenient class which takes the BufferedImage in the constructor and exposes an equivalent getRBG(x,y) method which makes it a drop in replacement for code using BufferedImage.getRGB(x,y)

    import java.awt.image.BufferedImage;
    import java.awt.image.DataBufferByte;
    
    public class FastRGB
    {
    
        private int width;
        private int height;
        private boolean hasAlphaChannel;
        private int pixelLength;
        private byte[] pixels;
    
        FastRGB(BufferedImage image)
        {
    
            pixels = ((DataBufferByte) image.getRaster().getDataBuffer()).getData();
            width = image.getWidth();
            height = image.getHeight();
            hasAlphaChannel = image.getAlphaRaster() != null;
            pixelLength = 3;
            if (hasAlphaChannel)
            {
                pixelLength = 4;
            }
    
        }
    
        int getRGB(int x, int y)
        {
            int pos = (y * pixelLength * width) + (x * pixelLength);
    
            int argb = -16777216; // 255 alpha
            if (hasAlphaChannel)
            {
                argb = (((int) pixels[pos++] & 0xff) << 24); // alpha
            }
    
            argb += ((int) pixels[pos++] & 0xff); // blue
            argb += (((int) pixels[pos++] & 0xff) << 8); // green
            argb += (((int) pixels[pos++] & 0xff) << 16); // red
            return argb;
        }
    }
    

提交回复
热议问题