Java ImageIcon fitToSquare(ImageIcon icon, int newSize)

Here you can find the source of fitToSquare(ImageIcon icon, int newSize)

Description

Scale an image to fit in a square of the given size, preserving aspect ratio.

License

Open Source License

Parameter

Parameter Description
icon a parameter
newSize a parameter

Declaration

public static ImageIcon fitToSquare(ImageIcon icon, int newSize) 

Method Source Code

//package com.java2s;
/**/*from   w w w. ja va  2s  .co  m*/
 * $RCSfile: ,v $
 * $Revision: $
 * $Date: $
 * 
 * Copyright (C) 2004-2011 Jive Software. All rights reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

import java.awt.Image;

import javax.swing.ImageIcon;

public class Main {
    /**
     * Scale an image to fit in a square of the given size, preserving aspect
     * ratio.
     *
     * @param icon
     * @param newSize
     * @return
     */
    public static ImageIcon fitToSquare(ImageIcon icon, int newSize) {
        if (newSize <= 0) {
            return icon;
        }

        final int oldWidth = icon.getIconWidth();
        final int oldHeight = icon.getIconHeight();
        int newWidth;
        int newHeight;

        if (oldHeight >= oldWidth) {
            newWidth = (int) ((float) oldWidth * newSize / oldHeight);
            newHeight = newSize;
        } else {
            newWidth = newSize;
            newHeight = (int) ((float) oldHeight * newSize / oldWidth);
        }

        final Image img = icon.getImage().getScaledInstance(newWidth,
                newHeight, Image.SCALE_SMOOTH);

        return new ImageIcon(img);
    }
}

Related

  1. createTempImage(ImageIcon icon, File oldFile)
  2. displayImage(final ImageIcon ii)
  3. drawImageBorder(Graphics g, ImageIcon img, Rectangle rect, Insets ins, boolean drawCenter)
  4. drawImageBorder(Graphics g, ImageIcon img, Rectangle rect, Insets ins, boolean drawCenter)
  5. fitIcon(ImageIcon icon, int containerWidth, int containerHeight)
  6. generateImageIcon(Color color, int size, Insets insets)
  7. getBorderedIcon(ImageIcon icon)
  8. getByteImage(ImageIcon icon)
  9. getDisabledIcon(ImageIcon icon)