Gets the BufferedImage as a 2D array of RGB pixel values - Java 2D Graphics

Java examples for 2D Graphics:BufferedImage Pixel

Description

Gets the BufferedImage as a 2D array of RGB pixel values

Demo Code


//package com.java2s;

import java.awt.image.BufferedImage;
import java.awt.image.PixelGrabber;

public class Main {
    /**/*from w w w  .  j a v  a 2 s .c om*/
     * Gets the BufferedImage as a 2D array of RGB pixel values
     * 
     * @param img
     * @return
     */
    public static int[][] getRGBPixels(BufferedImage img) {
        if (img == null)
            return null;
        int[][] result = null;
        try {
            PixelGrabber g = new PixelGrabber(img, 0, 0, -1, -1, true);
            g.grabPixels();
            int[] pixels = (int[]) g.getPixels();

            int w = g.getWidth(), h = g.getHeight();
            result = new int[w][h];

            for (int j = 0, count = 0; j < h; j++)
                for (int i = 0; i < w; i++)
                    result[i][j] = pixels[count++];

            return result;
        } catch (Exception ex) {
            ex.printStackTrace();
            return null;
        }
    }
}

Related Tutorials