Create a BufferedImage from an ImageProducer. - Java 2D Graphics

Java examples for 2D Graphics:BufferedImage

Description

Create a BufferedImage from an ImageProducer.

Demo Code


//package com.java2s;

import java.awt.image.*;

public class Main {
    /**//  ww  w. j a v a 2s  .  c  o  m
     * Create a BufferedImage from an ImageProducer.
     * @param producer the ImageProducer
     * @return a new TYPE_INT_ARGB BufferedImage
     */
    public static BufferedImage createImage(ImageProducer producer) {
        PixelGrabber pg = new PixelGrabber(producer, 0, 0, -1, -1, null, 0,
                0);
        try {
            pg.grabPixels();
        } catch (InterruptedException e) {
            throw new RuntimeException("Image fetch interrupted");
        }
        if ((pg.status() & ImageObserver.ABORT) != 0)
            throw new RuntimeException("Image fetch aborted");
        if ((pg.status() & ImageObserver.ERROR) != 0)
            throw new RuntimeException("Image fetch error");
        BufferedImage p = new BufferedImage(pg.getWidth(), pg.getHeight(),
                BufferedImage.TYPE_INT_ARGB);
        p.setRGB(0, 0, pg.getWidth(), pg.getHeight(),
                (int[]) pg.getPixels(), 0, pg.getWidth());
        return p;
    }

    /**
     * A convenience method for setting ARGB pixels in an image. This tries to avoid the performance
     * penalty of BufferedImage.setRGB unmanaging the image.
     * @param image   a BufferedImage object
     * @param x       the left edge of the pixel block
     * @param y       the right edge of the pixel block
     * @param width   the width of the pixel arry
     * @param height  the height of the pixel arry
     * @param pixels  the array of pixels to set
     * @see #getRGB
     */
    public static void setRGB(BufferedImage image, int x, int y, int width,
            int height, int[] pixels) {
        int type = image.getType();
        if (type == BufferedImage.TYPE_INT_ARGB
                || type == BufferedImage.TYPE_INT_RGB)
            image.getRaster().setDataElements(x, y, width, height, pixels);
        else
            image.setRGB(x, y, width, height, pixels, 0, width);
    }
}

Related Tutorials