Resizes the image down (not up) so that it fits proportionally within the given bounds - Java 2D Graphics

Java examples for 2D Graphics:BufferedImage Resize

Description

Resizes the image down (not up) so that it fits proportionally within the given bounds

Demo Code

/* Copyright (c) 2011 Danish Maritime Authority.
 *
 * 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./*  w w w  . jav  a  2s .c om*/
 */
//package com.java2s;
import java.awt.AlphaComposite;

import java.awt.Graphics2D;

import java.awt.Image;

import java.awt.RenderingHints;

import java.awt.image.BufferedImage;

public class Main {
    /**
     * Resizes the image down (not up) so that it fits proportionally 
     * within the given bounds
     * 
     * @param originalImage
     * @param type the image type
     * @param width the maximum image width
     * @param height the maximum image height
     * @return the scaled image
     */
    public static Image resizeImage(Image originalImage, int type,
            int width, int height) {
        // Value of 0 means we don't care
        width = (width == 0) ? originalImage.getWidth(null) : width;
        height = (height == 0) ? originalImage.getHeight(null) : height;

        // Check if we need to scale at all
        if (originalImage.getWidth(null) <= width
                && originalImage.getHeight(null) <= height) {
            return originalImage;
        }

        float scaleW = (float) originalImage.getWidth(null) / (float) width;
        float scaleH = (float) originalImage.getHeight(null)
                / (float) height;
        float scale = Math.max(scaleW, scaleH);

        int newWidth = (int) ((float) originalImage.getWidth(null) / scale);
        int newHeight = (int) ((float) originalImage.getHeight(null) / scale);

        BufferedImage resizedImage = new BufferedImage(newWidth, newHeight,
                type);
        Graphics2D g = resizedImage.createGraphics();
        g.setComposite(AlphaComposite.Src);
        g.setRenderingHint(RenderingHints.KEY_INTERPOLATION,
                RenderingHints.VALUE_INTERPOLATION_BILINEAR);
        g.setRenderingHint(RenderingHints.KEY_RENDERING,
                RenderingHints.VALUE_RENDER_QUALITY);
        g.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
                RenderingHints.VALUE_ANTIALIAS_ON);
        g.drawImage(originalImage, 0, 0, newWidth, newHeight, null);
        g.dispose();

        return resizedImage;
    }
}

Related Tutorials