Here you can find the source of resize(Icon icon, int width, int height)
Parameter | Description |
---|---|
icon | the icon to resize. |
width | the width of the icon or 0 or smaller when the width should be relative to the size of the icon and the provided height. Not both height and width can be smaller than 0. |
height | the height of the icon or 0 or smaller when the height should be relative to the size of the icon and the provided width. Not both height and width can be smaller than 0. |
public static Icon resize(Icon icon, int width, int height)
//package com.java2s; import java.awt.Graphics2D; import java.awt.GraphicsConfiguration; import java.awt.GraphicsDevice; import java.awt.GraphicsEnvironment; import java.awt.Image; import java.awt.image.BufferedImage; import javax.swing.Icon; import javax.swing.ImageIcon; public class Main { /**/*from w ww .j a v a 2 s . c o m*/ * Resizes an icon. * * @param icon * the icon to resize. * @param width * the width of the icon or 0 or smaller when the width should be * relative to the size of the icon and the provided height. Not * both height and width can be smaller than 0. * @param height * the height of the icon or 0 or smaller when the height should * be relative to the size of the icon and the provided width. * Not both height and width can be smaller than 0. * @return the resized icon. */ public static Icon resize(Icon icon, int width, int height) { if (icon == null) { return icon; } if ((height <= 0 || height == icon.getIconHeight()) && (width <= 0 || width == icon.getIconWidth())) { return icon; } Image image = iconToImage(icon); if (height <= 0) { height = (int) (icon.getIconHeight() / (float) (icon.getIconWidth() / width)); } if (width <= 0) { width = (int) (icon.getIconWidth() / (float) (icon.getIconHeight() / height)); } return new ImageIcon(image.getScaledInstance(width, height, Image.SCALE_SMOOTH)); } /** * Converts an Icon to an Image. * * @param icon * the icon to convert. * @return image the converted icon. */ public static Image iconToImage(Icon icon) { if (icon instanceof ImageIcon) { return ((ImageIcon) icon).getImage(); } int w = icon.getIconWidth(); int h = icon.getIconHeight(); GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment(); GraphicsDevice gd = ge.getDefaultScreenDevice(); GraphicsConfiguration gc = gd.getDefaultConfiguration(); BufferedImage image = gc.createCompatibleImage(w, h); Graphics2D g = image.createGraphics(); icon.paintIcon(null, g, 0, 0); g.dispose(); return image; } }