Here you can find the source of fitIcon(ImageIcon icon, int containerWidth, int containerHeight)
public static ImageIcon fitIcon(ImageIcon icon, int containerWidth, int containerHeight)
//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; } }