Java Image to BufferedImage toBufferedImage(Image image, int type)

Here you can find the source of toBufferedImage(Image image, int type)

Description

Create a BufferedImage from the given image

License

Open Source License

Parameter

Parameter Description
image The image
type BufferedImage type

Return

The BufferedImage

Declaration

public static BufferedImage toBufferedImage(Image image, int type) 

Method Source Code


//package com.java2s;
/*/* w ww.j  av a2  s .c  o  m*/
 * Copyright 1997-2016 Unidata Program Center/University Corporation for
 * Atmospheric Research, P.O. Box 3000, Boulder, CO 80307,
 * support@unidata.ucar.edu.
 * 
 * This library is free software; you can redistribute it and/or modify it
 * under the terms of the GNU Lesser General Public License as published by
 * the Free Software Foundation; either version 2.1 of the License, or (at
 * your option) any later version.
 * 
 * This library is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU Lesser
 * General Public License for more details.
 * 
 * You should have received a copy of the GNU Lesser General Public License
 * along with this library; if not, write to the Free Software Foundation,
 * Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
 */

import java.awt.Color;
import java.awt.Component;

import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.GraphicsConfiguration;
import java.awt.GraphicsDevice;
import java.awt.GraphicsEnvironment;
import java.awt.HeadlessException;
import java.awt.Image;

import java.awt.Toolkit;
import java.awt.Transparency;

import java.awt.image.BufferedImage;
import java.awt.image.ColorModel;
import java.awt.image.FilteredImageSource;
import java.awt.image.ImageFilter;

import java.awt.image.ImageProducer;
import java.awt.image.PixelGrabber;
import java.awt.image.RGBImageFilter;

import javax.swing.ImageIcon;

import javax.swing.JEditorPane;

import javax.swing.RepaintManager;

public class Main {
    /**
     * This method returns a buffered image with the contents of an image
     *
     * @param image  the image
     *
     * @return  a buffered image
     */
    public static BufferedImage toBufferedImage(Image image) {
        return toBufferedImage(image, false);
    }

    /**
     * This method returns a buffered image with the contents of an image
     *
     * @param image  the image
     * @param force If false then just return the image argument if its a BufferedImage
     *
     * @return  a buffered image
     */
    public static BufferedImage toBufferedImage(Image image, boolean force) {
        if (!force && (image instanceof BufferedImage)) {
            return (BufferedImage) image;
        }

        // This code ensures that all the pixels in the image are loaded
        image = new ImageIcon(image).getImage();

        // Determine if the image has transparent pixels; for this method's
        // implementation, see e661 Determining If an Image Has Transparent Pixels
        boolean hasAlpha = hasAlpha(image);

        // Create a buffered image with a format that's compatible with the screen
        BufferedImage bimage = null;
        GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();

        try {

            // Determine the type of transparency of the new buffered image
            int transparency = Transparency.OPAQUE;

            if (hasAlpha) {
                transparency = Transparency.BITMASK;
            }

            // Create the buffered image
            GraphicsDevice gs = ge.getDefaultScreenDevice();
            GraphicsConfiguration gc = gs.getDefaultConfiguration();

            bimage = gc.createCompatibleImage(image.getWidth(null), image.getHeight(null), transparency);
        } catch (HeadlessException e) {

            // The system does not have a screen
        }

        if (bimage == null) {

            // Create a buffered image using the default color model
            int type = BufferedImage.TYPE_INT_RGB;

            if (hasAlpha) {
                type = BufferedImage.TYPE_INT_ARGB;
            }

            bimage = new BufferedImage(image.getWidth(null), image.getHeight(null), type);
        }

        // Copy image to buffered image
        Graphics g = bimage.createGraphics();

        // Paint the image onto the buffered image
        g.drawImage(image, 0, 0, null);
        g.dispose();

        return bimage;
    }

    /**
     * Create a BufferedImage from the given image
     *
     * @param image The image
     * @param type BufferedImage type
     *
     * @return The BufferedImage
     */
    public static BufferedImage toBufferedImage(Image image, int type) {
        int w = image.getWidth(null);
        int h = image.getHeight(null);

        // System.err.println("tobuffered:" + w +"/" +h);
        BufferedImage bImage = new BufferedImage(w, h, type);

        bImage.getGraphics().drawImage(image, 0, 0, null);

        return bImage;
    }

    /**
     * Get the screen image from the component
     *
     * @param component The component.
     * @return Its image
     *
     * @throws Exception
     */
    public static Image getImage(Component component) throws Exception {
        RepaintManager repaintManager = RepaintManager.currentManager(component);
        double w = component.getWidth();
        double h = component.getHeight();

        if ((w == 0) || (h == 0)) {
            return null;
        }

        BufferedImage image = new BufferedImage((int) w, (int) h, BufferedImage.TYPE_INT_ARGB);

        repaintManager.setDoubleBufferingEnabled(false);

        Graphics2D g = (Graphics2D) image.getGraphics();

        component.paint(g);
        repaintManager.setDoubleBufferingEnabled(true);

        // component.repaint();
        // RepaintManager.setCurrentManager(manager);
        return image;
    }

    /**
     * Get an image from the component
     *
     * @param editor component
     * @param transparentColor if non null then set this color to be transparent
     *
     * @return image
     *
     * @throws Exception on badness
     */
    public static Image getImage(JEditorPane editor, Color transparentColor) throws Exception {
        editor.setBackground(transparentColor);

        Image i = getImage(editor);

        if (transparentColor != null) {
            i = makeColorTransparent(i, transparentColor);
        }

        return i;
    }

    /**
     * Check to see if the image has alpha
     *
     * @param image  the image
     *
     * @return true if has alpha
     */
    public static boolean hasAlpha(Image image) {

        // If buffered image, the color model is readily available
        if (image instanceof BufferedImage) {
            BufferedImage bimage = (BufferedImage) image;

            return bimage.getColorModel().hasAlpha();
        }

        // Use a pixel grabber to retrieve the image's color model;
        // grabbing a single pixel is usually sufficient
        PixelGrabber pg = new PixelGrabber(image, 0, 0, 1, 1, false);

        try {
            pg.grabPixels();
        } catch (InterruptedException e) {
        }

        // Get the image's color model
        ColorModel cm = pg.getColorModel();

        return cm.hasAlpha();
    }

    /**
     * Make a color in the image transparent
     *
     * @param im  image
     * @param c  the color to make transparent
     *
     * @return  a new image with the color transparent.
     */
    public static BufferedImage makeColorTransparent(Image im, Color c) {
        int[] redRange = { 0, 0 };
        int[] greenRange = { 0, 0 };
        int[] blueRange = { 0, 0 };

        if (c != null) {
            redRange[0] = redRange[1] = c.getRed();
            greenRange[0] = greenRange[1] = c.getGreen();
            blueRange[0] = blueRange[1] = c.getBlue();
        }

        return makeColorTransparent(im, redRange, greenRange, blueRange);
    }

    /**
     * Set the colors taht are within the given red, green and blue ranges to be transparent.
     *
     * @param im The image
     * @param redRange   red range
     * @param greenRange green range
     * @param blueRange blue range
     *
     * @return munged image
     */
    public static BufferedImage makeColorTransparent(Image im, final int[] redRange, final int[] greenRange,
            final int[] blueRange) {

        // GuiUtils.showDialog("writing image", new JLabel(new ImageIcon(im)));
        // System.err.println ("rgb:" + redRange[0]+"/"+ greenRange[0]+"/"+ blueRange[0]);
        ImageFilter filter = new RGBImageFilter() {
            public final int filterRGB(int x, int y, int rgb) {
                int red = (rgb >> 16) & 0xff;
                int green = (rgb >> 8) & 0xff;
                int blue = (rgb) & 0xff;

                if ((red >= redRange[0]) && (red <= redRange[1]) && (green >= greenRange[0])
                        && (green <= greenRange[1]) && (blue >= blueRange[0]) && (blue <= blueRange[1])) {
                    return 0x00FFFFFF & rgb;
                } else {
                    return rgb;
                }
            }
        };
        ImageProducer ip = new FilteredImageSource(im.getSource(), filter);

        im = Toolkit.getDefaultToolkit().createImage(ip);

        // GuiUtils.showDialog("writing image", new JLabel(new ImageIcon(im)));
        BufferedImage bim = toBufferedImage(im);

        return bim;
    }
}

Related

  1. toBufferedImage(Image image)
  2. toBufferedImage(Image image)
  3. toBufferedImage(Image image)
  4. toBufferedImage(Image image)
  5. toBufferedImage(Image image)
  6. toBufferedImage(Image image, int x, int y)
  7. toBufferedImage(Image img)
  8. toBufferedImage(Image img)
  9. toBufferedImage2(Image image)