Java - get pixel array from image

后端 未结 7 1071
面向向阳花
面向向阳花 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:20

    Mota's answer is great unless your BufferedImage came from a Monochrome Bitmap. A Monochrome Bitmap has only 2 possible values for its pixels (for example 0 = black and 1 = white). When a Monochrome Bitmap is used then the

    final byte[] pixels = ((DataBufferByte) image.getRaster().getDataBuffer()).getData();
    

    call returns the raw Pixel Array data in such a fashion that each byte contains more than one pixel.

    So when you use a Monochrome Bitmap image to create your BufferedImage object then this is the algorithm you want to use:

    /**
     * This returns a true bitmap where each element in the grid is either a 0
     * or a 1. A 1 means the pixel is white and a 0 means the pixel is black.
     * 
     * If the incoming image doesn't have any pixels in it then this method
     * returns null;
     * 
     * @param image
     * @return
     */
    public static int[][] convertToArray(BufferedImage image)
    {
    
        if (image == null || image.getWidth() == 0 || image.getHeight() == 0)
            return null;
    
        // This returns bytes of data starting from the top left of the bitmap
        // image and goes down.
        // Top to bottom. Left to right.
        final byte[] pixels = ((DataBufferByte) image.getRaster()
                .getDataBuffer()).getData();
    
        final int width = image.getWidth();
        final int height = image.getHeight();
    
        int[][] result = new int[height][width];
    
        boolean done = false;
        boolean alreadyWentToNextByte = false;
        int byteIndex = 0;
        int row = 0;
        int col = 0;
        int numBits = 0;
        byte currentByte = pixels[byteIndex];
        while (!done)
        {
            alreadyWentToNextByte = false;
    
            result[row][col] = (currentByte & 0x80) >> 7;
            currentByte = (byte) (((int) currentByte) << 1);
            numBits++;
    
            if ((row == height - 1) && (col == width - 1))
            {
                done = true;
            }
            else
            {
                col++;
    
                if (numBits == 8)
                {
                    currentByte = pixels[++byteIndex];
                    numBits = 0;
                    alreadyWentToNextByte = true;
                }
    
                if (col == width)
                {
                    row++;
                    col = 0;
    
                    if (!alreadyWentToNextByte)
                    {
                        currentByte = pixels[++byteIndex];
                        numBits = 0;
                    }
                }
            }
        }
    
        return result;
    }
    

提交回复
热议问题