Java ImageIcon Scale scaleImageIcon(String filePath, double maxHeight)

Here you can find the source of scaleImageIcon(String filePath, double maxHeight)

Description

scale Image Icon

License

Open Source License

Declaration

public static ImageIcon scaleImageIcon(String filePath, double maxHeight) 

Method Source Code

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

import javax.swing.*;
import java.awt.*;

public class Main {
    public static ImageIcon scaleImageIcon(String filePath, double maxHeight) {
        ImageIcon icon = new ImageIcon(filePath);
        double scaleFactor = maxHeight / icon.getIconHeight();
        Image image = icon.getImage().getScaledInstance(
                (int) (icon.getIconWidth() * scaleFactor), (int) maxHeight,
                Image.SCALE_SMOOTH);
        icon.setImage(image);//from   ww w.ja va 2s .  co  m
        return icon;
    }

    public static ImageIcon scaleImageIcon(String filePath, int maxHeight,
            int maxWidth) {
        ImageIcon icon = new ImageIcon(filePath);

        Dimension largestDimension = new Dimension(maxWidth, maxHeight);

        // Original size
        int imageWidth = icon.getIconWidth();
        int imageHeight = icon.getIconHeight();

        float aspectRatio = (float) imageWidth / imageHeight;

        if (imageWidth > maxWidth || imageHeight > maxHeight) {
            if ((float) largestDimension.width / largestDimension.height > aspectRatio) {
                largestDimension.width = (int) Math
                        .ceil(largestDimension.height * aspectRatio);
            } else {
                largestDimension.height = (int) Math
                        .ceil(largestDimension.width / aspectRatio);
            }

            imageWidth = largestDimension.width;
            imageHeight = largestDimension.height;
        }

        Image image = icon.getImage().getScaledInstance(imageWidth,
                imageHeight, Image.SCALE_SMOOTH);
        icon.setImage(image);
        return icon;
    }
}

Related

  1. scaleImage(ImageIcon icon)
  2. scaleImage(ImageIcon src, int width, int height)
  3. scaleImageIcon(ImageIcon icon, float scale, int hints)
  4. scaleImageIcon(ImageIcon icon, int newHeight, int newWidth)
  5. scaleImageIcon(ImageIcon icon, int w, int h)
  6. scaleImageIconTo(ImageIcon source, int height, int width)