get Limited Size Image - Java 2D Graphics

Java examples for 2D Graphics:Image Size

Description

get Limited Size Image

Demo Code


//package com.java2s;

import java.awt.Image;

import java.awt.image.BufferedImage;

public class Main {
    public static Image getLimitedSizeImage(BufferedImage image,
            double maxWidth, double maxHeight) {
        int width = image.getWidth();
        int height = image.getHeight();

        if (height > maxHeight) {
            if (width > maxWidth) {
                if (width / maxWidth > height / maxHeight) {
                    height *= (maxWidth / width);
                    width = (int) (maxWidth);
                } else {
                    width *= (maxHeight / height);
                    height = (int) maxHeight;
                }/*  w  ww.  ja  v  a 2  s.c om*/
            } else {
                width *= (maxHeight / height);
                height = (int) maxHeight;
            }
        } else if (width > maxWidth) {
            height *= (maxWidth / width);
            width = (int) (maxWidth);
        }

        return image.getScaledInstance(width, height,
                BufferedImage.SCALE_SMOOTH);
    }
}

Related Tutorials