Example usage for java.awt Transparency OPAQUE

List of usage examples for java.awt Transparency OPAQUE

Introduction

In this page you can find the example usage for java.awt Transparency OPAQUE.

Prototype

int OPAQUE

To view the source code for java.awt Transparency OPAQUE.

Click Source Link

Document

Represents image data that is guaranteed to be completely opaque, meaning that all pixels have an alpha value of 1.0.

Usage

From source file:net.rptools.maptool.client.ui.ExportDialog.java

/**
 * This is the top-level screen-capture routine. It sends the resulting PNG
 * image to the location previously selected by the user. TODO: It currently
 * calls {@link MapTool#takeMapScreenShot()} for "normal" screenshots, but
 * that's just until this code is considered stable enough.
 * //  w w  w.j  a  v  a  2s . c  om
 * @throws Exception
 */
@SuppressWarnings("unused")
public void screenCapture() throws Exception {
    MapTool.getFrame().setStatusMessage(I18N.getString("dialog.screenshot.msg.GeneratingScreenshot"));
    ExportRadioButtons type = ExportRadioButtons.getType();
    Player.Role role;
    try {
        switch (type) {
        case TYPE_CURRENT_VIEW:
            // This uses the original screenshot code: I didn't want to touch it, so I need
            // to pass it the same parameter it took before.
            role = ExportRadioButtons.VIEW_GM.isChecked() ? Player.Role.GM : Player.Role.PLAYER;
            BufferedImage screenCap = MapTool.takeMapScreenShot(renderer.getPlayerView(role));
            // since old screenshot code doesn't throw exceptions, look for null
            if (screenCap == null) {
                throw new Exception(I18N.getString("dialog.screenshot.error.failedImageGeneration"));
            }
            MapTool.getFrame().setStatusMessage(I18N.getString("dialog.screenshot.msg.screenshotStreaming"));
            ByteArrayOutputStream imageOut = new ByteArrayOutputStream();
            try {
                ImageIO.write(screenCap, "png", imageOut);
                screenCap = null; // Free up the memory as soon as possible
                MapTool.getFrame().setStatusMessage(I18N.getString("dialog.screenshot.msg.screenshotSaving"));
                exportLocation
                        .putContent(new BufferedInputStream(new ByteArrayInputStream(imageOut.toByteArray())));
            } finally {
                IOUtils.closeQuietly(imageOut);
            }
            MapTool.getFrame().setStatusMessage(I18N.getString("dialog.screenshot.msg.screenshotSaved"));
            break;
        case TYPE_ENTIRE_MAP:
            switchToWaitPanel();
            if (interactPanel.isSelected("METHOD_BUFFERED_IMAGE")
                    || interactPanel.isSelected("METHOD_IMAGE_WRITER")) {
                // Using a buffer in memory for the whole image
                try {
                    final PlayerView view = preScreenshot();
                    final ImageWriter pngWriter = ImageIO.getImageWritersByFormatName("png").next();
                    MapTool.getFrame()
                            .setStatusMessage(I18N.getString("dialog.screenshot.msg.screenshotStreaming"));

                    BufferedImage image;
                    if (interactPanel.isSelected("METHOD_BUFFERED_IMAGE")) {
                        image = new BufferedImage(renderer.getWidth(), renderer.getHeight(),
                                Transparency.OPAQUE);
                        final Graphics2D g = image.createGraphics();
                        //                     g.setClip(0, 0, renderer.getWidth(), renderer.getHeight());
                        renderer.renderZone(g, view);
                        g.dispose();
                    } else {
                        image = new ZoneImageGenerator(renderer, view);
                    }
                    // putContent() can consume quite a bit of time; really should have a progress
                    // meter of some kind here.
                    exportLocation.putContent(pngWriter, image);
                    if (image instanceof ZoneImageGenerator) {
                        log.debug("ZoneImageGenerator() stats: " + image.toString());
                    }
                    MapTool.getFrame()
                            .setStatusMessage(I18N.getString("dialog.screenshot.msg.screenshotSaving"));
                } catch (Exception e) {
                    MapTool.getFrame()
                            .setStatusMessage(I18N.getString("dialog.screenshot.error.failedImageGeneration"));
                } finally {
                    postScreenshot();
                    MapTool.getFrame()
                            .setStatusMessage(I18N.getString("dialog.screenshot.msg.screenshotSaved"));
                }
            } else if (interactPanel.isSelected("METHOD_BACKGROUND")) {
                // We must call preScreenshot before creating the ZoneImageGenerator, because
                // ZoneImageGenerator uses the ZoneRenderer's bounds to set itself up

                MapTool.showError("This doesn't work! Try one of the other methods.", null);
                if (false) {
                    //
                    // Note: this implementation is the obvious way, which doesn't work, since
                    // ZoneRenderer is part of the Swing component chain, and the threads get deadlocked.
                    //
                    // The suggested implementation by
                    // "Reiger" at http://ubuntuforums.org/archive/index.php/t-1455270.html
                    // might work... except that it would have to be part of ZoneRenderer
                    //
                    // The only way to make this really work is to pull the renderZone function
                    // out of ZoneRenderer into a new class: call it ZoneRasterizer. Then make
                    // ZoneRenderer create an instance of it, and patch up the code to make it
                    // compatible. Then we can create an instance of ZoneRasterizer, and run it
                    // in a separate thread, since it won't lock in any of the functions that
                    // Swing uses.
                    //
                    class backscreenRender implements Runnable {
                        public void run() {
                            try {
                                PlayerView view = preScreenshot();
                                final ZoneImageGenerator zoneImageGenerator = new ZoneImageGenerator(renderer,
                                        view);
                                final ImageWriter pngWriter = ImageIO.getImageWritersByFormatName("png").next();
                                exportLocation.putContent(pngWriter, zoneImageGenerator);
                                // postScreenshot is called by the callback imageComplete()
                            } catch (Exception e) {
                                assert false : "Unhandled Exception in renderOffScreen: '" + e.getMessage()
                                        + "'";
                            }
                        }
                    }
                    backscreenRender p = new backscreenRender();
                    new Thread(p).start();
                    repaint();
                }
            } else {
                throw new Exception("Unknown rendering method!");
            }
            break;
        default:
            throw new Exception(I18N.getString("dialog.screenshot.error.invalidDialogSettings"));
        }
    } catch (OutOfMemoryError e) {
        MapTool.showError("screenCapture() caught: Out Of Memory", e);
    } catch (Exception ex) {
        MapTool.showError("screenCapture() caught: ", ex);
    }
}

From source file:com.t3.client.ui.ExportDialog.java

/**
 * This is the top-level screen-capture routine. It sends the resulting PNG
 * image to the location previously selected by the user. TODO: It currently
 * calls {@link TabletopTool#takeMapScreenShot()} for "normal" screenshots, but
 * that's just until this code is considered stable enough.
 * /*from ww  w. j  av a2 s.com*/
 * @throws Exception
 */
@SuppressWarnings("unused")
public void screenCapture() throws Exception {
    TabletopTool.getFrame().setStatusMessage(I18N.getString("dialog.screenshot.msg.GeneratingScreenshot"));
    ExportRadioButtons type = ExportRadioButtons.getType();
    Player.Role role;
    try {
        switch (type) {
        case TYPE_CURRENT_VIEW:
            // This uses the original screenshot code: I didn't want to touch it, so I need
            // to pass it the same parameter it took before.
            role = ExportRadioButtons.VIEW_GM.isChecked() ? Player.Role.GM : Player.Role.PLAYER;
            BufferedImage screenCap = TabletopTool.takeMapScreenShot(renderer.getPlayerView(role));
            // since old screenshot code doesn't throw exceptions, look for null
            if (screenCap == null) {
                throw new Exception(I18N.getString("dialog.screenshot.error.failedImageGeneration"));
            }
            TabletopTool.getFrame()
                    .setStatusMessage(I18N.getString("dialog.screenshot.msg.screenshotStreaming"));
            ByteArrayOutputStream imageOut = new ByteArrayOutputStream();
            try {
                ImageIO.write(screenCap, "png", imageOut);
                screenCap = null; // Free up the memory as soon as possible
                TabletopTool.getFrame()
                        .setStatusMessage(I18N.getString("dialog.screenshot.msg.screenshotSaving"));
                exportLocation
                        .putContent(new BufferedInputStream(new ByteArrayInputStream(imageOut.toByteArray())));
            } finally {
                IOUtils.closeQuietly(imageOut);
            }
            TabletopTool.getFrame().setStatusMessage(I18N.getString("dialog.screenshot.msg.screenshotSaved"));
            break;
        case TYPE_ENTIRE_MAP:
            switchToWaitPanel();
            if (interactPanel.isSelected("METHOD_BUFFERED_IMAGE")
                    || interactPanel.isSelected("METHOD_IMAGE_WRITER")) {
                // Using a buffer in memory for the whole image
                try {
                    final PlayerView view = preScreenshot();
                    final ImageWriter pngWriter = ImageIO.getImageWritersByFormatName("png").next();
                    TabletopTool.getFrame()
                            .setStatusMessage(I18N.getString("dialog.screenshot.msg.screenshotStreaming"));

                    BufferedImage image;
                    if (interactPanel.isSelected("METHOD_BUFFERED_IMAGE")) {
                        image = new BufferedImage(renderer.getWidth(), renderer.getHeight(),
                                Transparency.OPAQUE);
                        final Graphics2D g = image.createGraphics();
                        //                     g.setClip(0, 0, renderer.getWidth(), renderer.getHeight());
                        renderer.renderZone(g, view);
                        g.dispose();
                    } else {
                        image = new ZoneImageGenerator(renderer, view);
                    }
                    // putContent() can consume quite a bit of time; really should have a progress
                    // meter of some kind here.
                    exportLocation.putContent(pngWriter, image);
                    if (image instanceof ZoneImageGenerator) {
                        log.debug("ZoneImageGenerator() stats: " + image.toString());
                    }
                    TabletopTool.getFrame()
                            .setStatusMessage(I18N.getString("dialog.screenshot.msg.screenshotSaving"));
                } catch (Exception e) {
                    TabletopTool.getFrame()
                            .setStatusMessage(I18N.getString("dialog.screenshot.error.failedImageGeneration"));
                } finally {
                    postScreenshot();
                    TabletopTool.getFrame()
                            .setStatusMessage(I18N.getString("dialog.screenshot.msg.screenshotSaved"));
                }
            } else if (interactPanel.isSelected("METHOD_BACKGROUND")) {
                // We must call preScreenshot before creating the ZoneImageGenerator, because
                // ZoneImageGenerator uses the ZoneRenderer's bounds to set itself up

                TabletopTool.showError("This doesn't work! Try one of the other methods.", null);
                if (false) {
                    //
                    // Note: this implementation is the obvious way, which doesn't work, since
                    // ZoneRenderer is part of the Swing component chain, and the threads get deadlocked.
                    //
                    // The suggested implementation by
                    // "Reiger" at http://ubuntuforums.org/archive/index.php/t-1455270.html
                    // might work... except that it would have to be part of ZoneRenderer
                    //
                    // The only way to make this really work is to pull the renderZone function
                    // out of ZoneRenderer into a new class: call it ZoneRasterizer. Then make
                    // ZoneRenderer create an instance of it, and patch up the code to make it
                    // compatible. Then we can create an instance of ZoneRasterizer, and run it
                    // in a separate thread, since it won't lock in any of the functions that
                    // Swing uses.
                    //
                    class backscreenRender implements Runnable {
                        @Override
                        public void run() {
                            try {
                                PlayerView view = preScreenshot();
                                final ZoneImageGenerator zoneImageGenerator = new ZoneImageGenerator(renderer,
                                        view);
                                final ImageWriter pngWriter = ImageIO.getImageWritersByFormatName("png").next();
                                exportLocation.putContent(pngWriter, zoneImageGenerator);
                                // postScreenshot is called by the callback imageComplete()
                            } catch (Exception e) {
                                assert false : "Unhandled Exception in renderOffScreen: '" + e.getMessage()
                                        + "'";
                            }
                        }
                    }
                    backscreenRender p = new backscreenRender();
                    new Thread(p).start();
                    repaint();
                }
            } else {
                throw new Exception("Unknown rendering method!");
            }
            break;
        default:
            throw new Exception(I18N.getString("dialog.screenshot.error.invalidDialogSettings"));
        }
    } catch (OutOfMemoryError e) {
        TabletopTool.showError("screenCapture() caught: Out Of Memory", e);
    } catch (Exception ex) {
        TabletopTool.showError("screenCapture() caught: ", ex);
    }
}

From source file:com.occamlab.te.parsers.ImageParser.java

private static Node processFrame(ImageReader reader, int frame, NodeList nodes, PrintWriter logger)
        throws Exception {
    if (nodes.getLength() == 0) {
        return null;
    }/*from w  w w  . ja v a 2  s.com*/
    String formatName = reader.getFormatName().toLowerCase(); // 2011-09-08
                                                              // PwD
    BufferedImage image = reader.read(frame);

    for (int i = 0; i < nodes.getLength(); i++) {
        Node node = nodes.item(i);
        if (node.getNodeType() == Node.ELEMENT_NODE) {
            // System.out.println(node.getLocalName());
            if (node.getLocalName().equals("type")) {
                node.setTextContent(formatName); // 2011-09-08 PwD was
                                                 // reader.getFormatName().toLowerCase()
            } else if (node.getLocalName().equals("height")) {
                node.setTextContent(Integer.toString(image.getHeight()));
            } else if (node.getLocalName().equals("width")) {
                node.setTextContent(Integer.toString(image.getWidth()));
            } else if (node.getLocalName().equals("metadata")) {
                try { // 2011--08-23 PwD
                    IIOMetadata metadata = reader.getImageMetadata(frame);
                    if (metadata != null) {
                        String format = ((Element) node).getAttribute("format");
                        if (format.length() == 0) {
                            format = metadata.getNativeMetadataFormatName();
                        }
                        Node tree = metadata.getAsTree(format);
                        TransformerFactory tf = TransformerFactory.newInstance();
                        Transformer t = tf.newTransformer();
                        t.transform(new DOMSource(tree), new DOMResult(node));
                    }
                } catch (javax.imageio.IIOException e) { // 2011--08-23 PwD
                    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
                    DocumentBuilder db = dbf.newDocumentBuilder();
                    Document doc = db.newDocument();
                    String format = reader.getFormatName().toLowerCase();
                    String formatEltName = "javax_imageio_" + format + "_1.0";
                    Element formatElt = doc.createElement(formatEltName);
                    TransformerFactory tf = TransformerFactory.newInstance();
                    Transformer t = tf.newTransformer();
                    t.transform(new DOMSource(formatElt), new DOMResult(node));
                }
            } else if (node.getLocalName().equals("model")) {
                int imagetype = -1;
                String model = ((Element) node).getAttribute("value");
                if (model.equals("MONOCHROME")) {
                    imagetype = BufferedImage.TYPE_BYTE_BINARY;
                } else if (model.equals("GRAY")) {
                    imagetype = BufferedImage.TYPE_BYTE_GRAY;
                } else if (model.equals("RGB")) {
                    imagetype = BufferedImage.TYPE_3BYTE_BGR;
                } else if (model.equals("ARGB")) {
                    imagetype = BufferedImage.TYPE_4BYTE_ABGR;
                } else {
                    model = "CUSTOM";
                }
                ((Element) node).setAttribute("value", model);
                BufferedImage buffImage = image;
                if (image.getType() != imagetype && imagetype != -1) {
                    buffImage = new BufferedImage(image.getWidth(), image.getHeight(), imagetype);
                    Graphics2D g2 = buffImage.createGraphics();
                    ImageTracker tracker = new ImageTracker();
                    boolean done = g2.drawImage(image, 0, 0, tracker);
                    if (!done) {
                        while (!tracker.done) {
                            sleep(50);
                        }
                    }
                }
                processBufferedImage(buffImage, formatName, node.getChildNodes());
            } else if (node.getLocalName().equals("transparency")) { // 2011-08-24
                                                                     // PwD
                int transparency = image.getTransparency();
                String transparencyName = null;
                switch (transparency) {
                case Transparency.OPAQUE: {
                    transparencyName = "Opaque";
                    break;
                }
                case Transparency.BITMASK: {
                    transparencyName = "Bitmask";
                    break;
                }
                case Transparency.TRANSLUCENT: {
                    transparencyName = "Translucent";
                    break;
                }
                default: {
                    transparencyName = "Unknown";
                }
                }
                node.setTextContent(transparencyName);

            } else if (node.getLocalName().equals("base64Data")) { // 2011-09-08
                                                                   // PwD
                String base64Data = getBase64Data(image, formatName, node);
                node.setTextContent(base64Data);
            } else {
                logger.println("ImageParser Error: Invalid tag " + node.getNodeName());
            }
        }
    }
    return null;
}

From source file:lucee.runtime.img.Image.java

private Object toStringTransparency(int transparency) {
    if (Transparency.OPAQUE == transparency)
        return "OPAQUE";
    if (Transparency.BITMASK == transparency)
        return "BITMASK";
    if (Transparency.TRANSLUCENT == transparency)
        return "TRANSLUCENT";
    return "Unknown type of transparency";
}

From source file:TextureByReference.java

public static BufferedImage convertToCustomRGBA(BufferedImage bImage) {
    if (bImage.getType() != BufferedImage.TYPE_INT_ARGB) {
        ImageOps.convertImage(bImage, BufferedImage.TYPE_INT_ARGB);
    }/*from ww  w. j a va 2  s .  com*/

    int width = bImage.getWidth();
    int height = bImage.getHeight();

    ColorSpace cs = ColorSpace.getInstance(ColorSpace.CS_sRGB);
    int[] nBits = { 8, 8, 8, 8 };
    ColorModel cm = new ComponentColorModel(cs, nBits, true, false, Transparency.OPAQUE, 0);
    int[] bandOffset = { 0, 1, 2, 3 };

    WritableRaster newRaster = Raster.createInterleavedRaster(DataBuffer.TYPE_BYTE, width, height, width * 4, 4,
            bandOffset, null);
    byte[] byteData = ((DataBufferByte) newRaster.getDataBuffer()).getData();
    Raster origRaster = bImage.getData();
    int[] pixel = new int[4];
    int k = 0;
    for (int j = 0; j < height; j++) {
        for (int i = 0; i < width; i++) {
            pixel = origRaster.getPixel(i, j, pixel);
            byteData[k++] = (byte) (pixel[0]);
            byteData[k++] = (byte) (pixel[1]);
            byteData[k++] = (byte) (pixel[2]);
            byteData[k++] = (byte) (pixel[3]);
        }
    }
    BufferedImage newImage = new BufferedImage(cm, newRaster, false, null);
    //  if (newImage.getType() == BufferedImage.TYPE_CUSTOM) {
    //    System.out.println("Type is custom");
    //  }
    return newImage;
}

From source file:TextureByReference.java

public static BufferedImage convertToCustomRGB(BufferedImage bImage) {
    if (bImage.getType() != BufferedImage.TYPE_INT_ARGB) {
        ImageOps.convertImage(bImage, BufferedImage.TYPE_INT_ARGB);
    }//  www  .  ja  v  a  2  s  .  co m

    int width = bImage.getWidth();
    int height = bImage.getHeight();

    ColorSpace cs = ColorSpace.getInstance(ColorSpace.CS_sRGB);
    int[] nBits = { 8, 8, 8 };
    ColorModel cm = new ComponentColorModel(cs, nBits, false, false, Transparency.OPAQUE, 0);
    int[] bandOffset = { 0, 1, 2 };

    WritableRaster newRaster = Raster.createInterleavedRaster(DataBuffer.TYPE_BYTE, width, height, width * 3, 3,
            bandOffset, null);
    byte[] byteData = ((DataBufferByte) newRaster.getDataBuffer()).getData();
    Raster origRaster = bImage.getData();
    int[] pixel = new int[4];
    int k = 0;
    for (int j = 0; j < height; j++) {
        for (int i = 0; i < width; i++) {
            pixel = origRaster.getPixel(i, j, pixel);
            byteData[k++] = (byte) (pixel[0]);
            byteData[k++] = (byte) (pixel[1]);
            byteData[k++] = (byte) (pixel[2]);
        }
    }
    BufferedImage newImage = new BufferedImage(cm, newRaster, false, null);
    //  if (newImage.getType() == BufferedImage.TYPE_CUSTOM) {
    //    System.out.println("Type is custom");
    //  }
    return newImage;
}

From source file:lucee.runtime.img.Image.java

/**
  * Convenience method that returns a scaled instance of the
  * provided {@code BufferedImage}./*w  w w.j  a v a2  s.co m*/
  *
  * @param img the original image to be scaled
  * @param targetWidth the desired width of the scaled instance,
  *    in pixels
  * @param targetHeight the desired height of the scaled instance,
  *    in pixels
  * @param hint one of the rendering hints that corresponds to
  *    {@code RenderingHints.KEY_INTERPOLATION} (e.g.
  *    {@code RenderingHints.VALUE_INTERPOLATION_NEAREST_NEIGHBOR},
  *    {@code RenderingHints.VALUE_INTERPOLATION_BILINEAR},
  *    {@code RenderingHints.VALUE_INTERPOLATION_BICUBIC})
  * @param higherQuality if true, this method will use a multi-step
  *    scaling technique that provides higher quality than the usual
  *    one-step technique (only useful in downscaling cases, where
  *    {@code targetWidth} or {@code targetHeight} is
  *    smaller than the original dimensions, and generally only when
  *    the {@code BILINEAR} hint is specified)
  * @return a scaled version of the original {@code BufferedImage}
  */
private BufferedImage getScaledInstance(BufferedImage img, int targetWidth, int targetHeight, Object hint,
        boolean higherQuality) {
    // functionality not supported in java 1.4
    int transparency = Transparency.OPAQUE;
    try {
        transparency = img.getTransparency();
    } catch (Throwable t) {
    }
    int type = (transparency == Transparency.OPAQUE) ? BufferedImage.TYPE_INT_RGB : BufferedImage.TYPE_INT_ARGB;

    BufferedImage ret = img;
    int w, h;
    if (higherQuality) {
        // Use multi-step technique: start with original size, then
        // scale down in multiple passes with drawImage()
        // until the target size is reached
        w = img.getWidth();
        h = img.getHeight();
    } else {
        // Use one-step technique: scale directly from original
        // size to target size with a single drawImage() call
        w = targetWidth;
        h = targetHeight;
    }

    do {
        if (higherQuality && w > targetWidth) {
            w /= 2;
            if (w < targetWidth) {
                w = targetWidth;
            }
        }

        if (higherQuality && h > targetHeight) {
            h /= 2;
            if (h < targetHeight) {
                h = targetHeight;
            }
        }

        BufferedImage tmp = new BufferedImage(w, h, type);
        Graphics2D g2 = tmp.createGraphics();
        g2.setRenderingHint(RenderingHints.KEY_INTERPOLATION, hint);
        g2.drawImage(ret, 0, 0, w, h, null);
        g2.dispose();

        ret = tmp;
    } while (w != targetWidth || h != targetHeight);

    return ret;
}

From source file:com.aurel.track.attachment.AttachBL.java

private static BufferedImage toBufferedImage(Image image) {
    if (image instanceof BufferedImage) {
        return (BufferedImage) image;
    }/*from   ww w .j a v a 2  s . c  o  m*/

    // 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 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;
}

From source file:net.pms.medialibrary.commons.helpers.FileImportHelper.java

/**
 * Creates a buffered image from an image
 * @param image the image/*from  ww w  .  j av  a  2 s  .c o  m*/
 * @return the buffered image
 */
public static BufferedImage getBufferedImage(Image image) {
    if (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 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;
}

From source file:lucee.runtime.img.Image.java

public static BufferedImage toBufferedImage(java.awt.Image image) {
    if (image instanceof BufferedImage) {
        return (BufferedImage) image;
    }// ww w .  j ava 2s  .c  o  m

    // 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
    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;
}