get Limited Size Image From Image - Java 2D Graphics

Java examples for 2D Graphics:Image Size

Description

get Limited Size Image From Image

Demo Code


//package com.java2s;
import java.awt.Graphics;
import java.awt.Image;

import java.awt.image.BufferedImage;

public class Main {
    public static Image getLimitedSizeImageFromImage(Image img,
            int maxWidth, int maxHeight) {
        return getLimitedSizeImage(getBufferedImage(img), maxWidth,
                maxHeight);/* w  w w .  j  a  va2 s .co m*/
    }

    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;
                }
            } 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);
    }

    public static BufferedImage getBufferedImage(Image image) {
        int width = image.getWidth(null);
        int height = image.getHeight(null);
        BufferedImage bufferedImage = new BufferedImage(width, height,
                BufferedImage.TYPE_INT_ARGB);
        Graphics g = bufferedImage.getGraphics();
        g.drawImage(image, 0, 0, null);
        g.dispose();
        return bufferedImage;
    }
}

Related Tutorials