Java examples for 2D Graphics:BufferedImage Pixel
Writes a rectangular area of pixels in the destination BufferedImage.
/*// w ww . j a v a2s. c o m * @(#)EffectUtils.java 1.2 07/12/12 * * Copyright 2007 Sun Microsystems, Inc. All rights reserved. * SUN PROPRIETARY/CONFIDENTIAL. Use is subject to license terms. */ //package com.java2s; import java.awt.image.BufferedImage; import java.awt.image.WritableRaster; public class Main { /** * <p> * Writes a rectangular area of pixels in the destination * <code>BufferedImage</code>. Calling this method on an image of type * different from <code>BufferedImage.TYPE_INT_ARGB</code> and * <code>BufferedImage.TYPE_INT_RGB</code> will unmanage the image. * </p> * * @param img * the destination image * @param x * the x location at which to start storing pixels * @param y * the y location at which to start storing pixels * @param w * the width of the rectangle of pixels to store * @param h * the height of the rectangle of pixels to store * @param pixels * an array of pixels, stored as integers * @throws IllegalArgumentException * is <code>pixels</code> is non-null and of length < w*h */ static void setPixels(BufferedImage img, int x, int y, int w, int h, byte[] pixels) { if (pixels == null || w == 0 || h == 0) { return; } else if (pixels.length < w * h) { throw new IllegalArgumentException( "pixels array must have a length >= w*h"); } int imageType = img.getType(); if (imageType == BufferedImage.TYPE_BYTE_GRAY) { WritableRaster raster = img.getRaster(); raster.setDataElements(x, y, w, h, pixels); } else { throw new IllegalArgumentException( "Only type BYTE_GRAY is supported"); } } /** * <p> * Writes a rectangular area of pixels in the destination * <code>BufferedImage</code>. Calling this method on an image of type * different from <code>BufferedImage.TYPE_INT_ARGB</code> and * <code>BufferedImage.TYPE_INT_RGB</code> will unmanage the image. * </p> * * @param img * the destination image * @param x * the x location at which to start storing pixels * @param y * the y location at which to start storing pixels * @param w * the width of the rectangle of pixels to store * @param h * the height of the rectangle of pixels to store * @param pixels * an array of pixels, stored as integers * @throws IllegalArgumentException * is <code>pixels</code> is non-null and of length < w*h */ public static void setPixels(BufferedImage img, int x, int y, int w, int h, int[] pixels) { if (pixels == null || w == 0 || h == 0) { return; } else if (pixels.length < w * h) { throw new IllegalArgumentException( "pixels array must have a length" + " >= w*h"); } int imageType = img.getType(); if (imageType == BufferedImage.TYPE_INT_ARGB || imageType == BufferedImage.TYPE_INT_RGB) { WritableRaster raster = img.getRaster(); raster.setDataElements(x, y, w, h, pixels); } else { // Unmanages the image img.setRGB(x, y, w, h, pixels, 0, w); } } }