Gets the array of all colors of the given image. - Java 2D Graphics

Java examples for 2D Graphics:BufferedImage Color

Description

Gets the array of all colors of the given image.

Demo Code


//package com.java2s;

import java.awt.Color;

import java.awt.Point;

import java.awt.image.BufferedImage;

public class Main {
    /**/*from   w  w  w  .j av a2 s .co  m*/
     * Gets the array of all colors of the given image.
     * 
     * @param image
     *            The image.
     * @return A two-dimensional array of the colors of the given image.
     */
    public static Color[][] getColors(final BufferedImage image) {
        final int w = image.getWidth();
        final int h = image.getHeight();
        final Color[][] colors = new Color[w][h];
        for (int x = 0; x < w; x++) {
            for (int y = 0; y < h; y++) {
                colors[x][y] = getColorAt(image, x, y);
            }
        }
        return colors;
    }

    /**
     * Gets the color at a given x-y coordinate on the given image.
     * 
     * @param image
     *            The image.
     * @param x
     *            The x coordinate.
     * @param y
     *            The y coordinate.
     * @return The color at the given coordinates.
     */
    public static Color getColorAt(final BufferedImage image, final int x,
            final int y) {
        if (x >= 0 && y >= 0 && x < image.getWidth()
                && y < image.getHeight()) {
            return new Color(image.getRGB(x, y));
        }
        return Color.BLACK;
    }

    /**
     * Gets the color at a given point on the given image.
     * 
     * @param image
     *            The image.
     * @param p
     *            The point.
     * @return The color at the given point.
     */
    public static Color getColorAt(final BufferedImage image, final Point p) {
        return getColorAt(image, p.x, p.y);
    }
}

Related Tutorials