Java ImageIcon Scale scale(ImageIcon icon, int maxWidth, int maxHeight)

Here you can find the source of scale(ImageIcon icon, int maxWidth, int maxHeight)

Description

scale

License

Open Source License

Declaration

public static ImageIcon scale(ImageIcon icon, int maxWidth, int maxHeight) 

Method Source Code

//package com.java2s;

import java.awt.Image;

import javax.swing.ImageIcon;

public class Main {
    public static ImageIcon scale(ImageIcon icon, int maxWidthAndHeight) {
        return scale(icon, maxWidthAndHeight, maxWidthAndHeight);
    }/*  w w  w.ja  va  2 s  .  c om*/

    public static ImageIcon scale(ImageIcon icon, int maxWidth, int maxHeight) {
        if (icon == null)
            return null;

        if (maxWidth >= icon.getIconWidth() && maxHeight >= icon.getIconHeight())
            return icon;

        int width = Math.min(maxWidth, icon.getIconWidth()), height = Math.min(maxHeight, icon.getIconHeight());

        float widthFactor = (float) width / icon.getIconWidth(),
                heightFactor = (float) height / icon.getIconHeight();

        if (widthFactor < heightFactor) {
            height = Math.round(widthFactor * icon.getIconHeight());
        } else if (heightFactor < widthFactor) {
            width = Math.round(heightFactor * icon.getIconWidth());
        }

        Image img = icon.getImage();
        Image newImg = img.getScaledInstance(width, height, Image.SCALE_SMOOTH);

        return new ImageIcon(newImg);
    }
}

Related

  1. getScaledImageIcon(final String location, final int width, final int height)
  2. getScaledImageIconHeight(ImageIcon ii, int h, boolean incr)
  3. rescale(ImageIcon src, Dimension newMinSize, ImageObserver observer)
  4. rescaleImageIcon(ImageIcon image, int size)
  5. scale(ImageIcon icon, int newHeight, int newWidth)
  6. scale(ImageIcon original, int width, int height)
  7. scaleIcon(final ImageIcon icon)
  8. scaleIcon(ImageIcon icon, int size)