Java ImageIcon fitIcon(ImageIcon icon, int containerWidth, int containerHeight)

Here you can find the source of fitIcon(ImageIcon icon, int containerWidth, int containerHeight)

Description

fit Icon

License

Open Source License

Declaration

public static ImageIcon fitIcon(ImageIcon icon, int containerWidth,
             int containerHeight) 

Method Source Code

//package com.java2s;
//License from project: Open Source License 

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

import javax.swing.ImageIcon;

public class Main {
    public static ImageIcon fitIcon(ImageIcon icon, int containerWidth,
            int containerHeight) {
        if (icon.getIconWidth() > containerWidth) {
            double rate = icon.getIconWidth() / (double) containerWidth;
            int height = (int) (icon.getIconHeight() / rate);
            int width = (int) (icon.getIconWidth() / rate);
            icon = new ImageIcon(getScaledImage(icon, width, height));
        } else if (icon.getIconHeight() > containerHeight) {
            double rate = icon.getIconHeight() / (double) containerHeight;
            int height = (int) (icon.getIconHeight() / rate);
            int width = (int) (icon.getIconWidth() / rate);
            icon = new ImageIcon(getScaledImage(icon, width, height));
        }//  w w  w .j  a v a2  s  .  com

        return icon;
    }

    public static Image getScaledImage(ImageIcon icon, int w, int h) {
        BufferedImage resizedImg = new BufferedImage(w, h,
                BufferedImage.TYPE_INT_ARGB);
        Graphics2D g2 = resizedImg.createGraphics();

        g2.setRenderingHint(RenderingHints.KEY_INTERPOLATION,
                RenderingHints.VALUE_INTERPOLATION_BILINEAR);
        g2.drawImage(icon.getImage(), 0, 0, w, h, null);
        g2.dispose();

        return resizedImg;
    }
}

Related

  1. CreateSizedImageIconScaledSmooth(URL filePath, int width, int height)
  2. createTempImage(ImageIcon icon, File oldFile)
  3. displayImage(final ImageIcon ii)
  4. drawImageBorder(Graphics g, ImageIcon img, Rectangle rect, Insets ins, boolean drawCenter)
  5. drawImageBorder(Graphics g, ImageIcon img, Rectangle rect, Insets ins, boolean drawCenter)
  6. fitToSquare(ImageIcon icon, int newSize)
  7. generateImageIcon(Color color, int size, Insets insets)
  8. getBorderedIcon(ImageIcon icon)
  9. getByteImage(ImageIcon icon)