Java Icon to Image iconToImage(@Nonnull Component context, @Nullable final Icon icon)

Here you can find the source of iconToImage(@Nonnull Component context, @Nullable final Icon icon)

Description

icon To Image

License

Apache License

Declaration

@Nonnull
    public static Image iconToImage(@Nonnull Component context, @Nullable final Icon icon) 

Method Source Code

//package com.java2s;
/*// ww w . j a v a 2s  . c o m
 * Copyright 2016 Igor Maznitsa.
 *
 * 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.Component;

import java.awt.Graphics;
import java.awt.Image;

import java.awt.image.BufferedImage;

import javax.annotation.Nonnull;
import javax.annotation.Nullable;

import javax.swing.Icon;
import javax.swing.ImageIcon;

public class Main {
    @Nonnull
    public static Image iconToImage(@Nonnull Component context, @Nullable final Icon icon) {
        if (icon instanceof ImageIcon) {
            return ((ImageIcon) icon).getImage();
        }
        final int width = icon == null ? 16 : icon.getIconWidth();
        final int height = icon == null ? 16 : icon.getIconHeight();
        final BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
        if (icon != null) {
            final Graphics g = image.getGraphics();
            try {
                icon.paintIcon(context, g, 0, 0);
            } finally {
                g.dispose();
            }
        }
        return image;
    }
}

Related

  1. iconImage(Icon icon)
  2. iconToImage(Icon icon)
  3. iconToImage(Icon icon)
  4. iconToImage(Icon icon)
  5. iconToImage(Icon icon)