get Pixels from BufferedImage - Java 2D Graphics

Java examples for 2D Graphics:BufferedImage Pixel

Description

get Pixels from BufferedImage

Demo Code


//package com.java2s;

import java.awt.image.BufferedImage;
import java.awt.image.Raster;

public class Main {
    public static int[] getPixels(BufferedImage img, int x, int y, int w,
            int h, int[] pixels) {
        if (w == 0 || h == 0) {
            return new int[0];
        }//from   w  w w  .  j a va 2s .c  o  m

        if (pixels == null) {
            pixels = new int[w * h];
        } else if (pixels.length < w * h) {
            throw new IllegalArgumentException(
                    "pixels array must have a length" + " >= w*h"); //$NON-NLS-1$ //$NON-NLS-2$
        }

        int imageType = img.getType();
        if (imageType == BufferedImage.TYPE_INT_ARGB
                || imageType == BufferedImage.TYPE_INT_RGB) {
            Raster raster = img.getRaster();
            return (int[]) raster.getDataElements(x, y, w, h, pixels);
        }

        // Unmanages the image
        return img.getRGB(x, y, w, h, pixels, 0, w);
    }
}

Related Tutorials