Java Icon to BufferedImage getBufferedImage(Icon icon)

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

Description

get Buffered Image

License

Apache License

Return

the icon, unmodified, as a Buffered Image

Declaration

public static BufferedImage getBufferedImage(Icon icon) 

Method Source Code


//package com.java2s;
/*//from w  ww.  j a  va  2  s .c o  m
 * Copyright 2016 dorkbox, llc
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

import java.awt.AlphaComposite;

import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.RenderingHints;
import java.awt.image.BufferedImage;

import javax.swing.Icon;

public class Main {
    /**
     * @return the image, unmodified, as a Buffered Image
     */
    public static BufferedImage getBufferedImage(Image image) {
        if (image instanceof BufferedImage) {
            return (BufferedImage) image;
        }

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

        Graphics2D g = bimage.createGraphics();
        g.addRenderingHints(new RenderingHints(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY));
        g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER));

        g.drawImage(image, 0, 0, null);
        g.dispose();

        // Return the buffered image
        return bimage;
    }

    /**
     * @return the icon, unmodified, as a Buffered Image
     */
    public static BufferedImage getBufferedImage(Icon icon) {
        if (icon instanceof BufferedImage) {
            return (BufferedImage) icon;
        }

        BufferedImage bimage = new BufferedImage(icon.getIconWidth(), icon.getIconHeight(),
                BufferedImage.TYPE_INT_ARGB);

        Graphics2D g = bimage.createGraphics();
        g.addRenderingHints(new RenderingHints(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY));
        g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER));

        icon.paintIcon(null, g, 0, 0);
        g.dispose();

        return bimage;
    }
}

Related

  1. getBufferedImage(Component comp, Icon icon)
  2. getBufferedImageFromIcon(Icon icon)
  3. iconToBufferedImage(Icon icon)
  4. toBufferedImage(Icon icon)
  5. toBufferedImage(Icon icon, int x, int y)