Java Image Create createImage(Icon icon)

Here you can find the source of createImage(Icon icon)

Description

Returns an image got by drawing an Icon.

License

LGPL

Parameter

Parameter Description
icon a parameter

Return

image

Declaration

private static BufferedImage createImage(Icon icon) 

Method Source Code


//package com.java2s;
//License from project: LGPL 

import java.awt.AlphaComposite;
import java.awt.Color;
import java.awt.Component;
import java.awt.Composite;

import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import javax.swing.Icon;

import javax.swing.JPanel;

public class Main {
    private static Component dummyComponent_;

    /**//  w  w  w  . j  a  va  2 s .c o m
     * Returns an image got by drawing an Icon.
     *
     * @param  icon
     * @return  image
     */
    private static BufferedImage createImage(Icon icon) {
        int w = icon.getIconWidth();
        int h = icon.getIconHeight();

        /* Create an image to draw on. */
        BufferedImage image = new BufferedImage(w, h, BufferedImage.TYPE_INT_ARGB);
        Graphics2D g2 = image.createGraphics();

        /* This ought to clear it to transparent white (00ffffff).
         * But in fact it seems to remain transparent black (00000000).
         * That shouldn't make a difference, but in some cases PNGs
         * written with a transparent background can end up displaying
         * with black backgrounds when they end up in PDFs (probably
         * a bug in Fop?).  I have wasted a vast amount of time trying
         * to get this right and so far failed.  But if you just want
         * to copy an existing image you can use AlphaComposite.SRC
         * for the actual painting. */
        Color color = g2.getColor();
        Composite compos = g2.getComposite();
        g2.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC));
        g2.setColor(new Color(1f, 1f, 1f, 0f));
        g2.fillRect(0, 0, w, h);
        g2.setColor(color);
        g2.setComposite(compos);

        /* Paint the icon. */
        icon.paintIcon(getDummyComponent(), g2, 0, 0);

        /* Tidy up and return the image. */
        g2.dispose();
        return image;
    }

    /**
     * Provides an empty component.
     *
     * @return   lazily constructed component
     */
    private static Component getDummyComponent() {
        if (dummyComponent_ == null) {
            dummyComponent_ = new JPanel();
        }
        return dummyComponent_;
    }
}

Related

  1. createImage(byte[] data)
  2. createImage(Component comp, Icon icon)
  3. createImage(JPanel panel)
  4. createImage(String str)
  5. createImage(URL url, String description, boolean checkPresence)
  6. createImageCopy(Image image)