Gets a scaled instance of the source image. - Java 2D Graphics

Java examples for 2D Graphics:BufferedImage Scale

Description

Gets a scaled instance of the source image.

Demo Code


//package com.java2s;
import java.awt.*;

import java.awt.image.*;

public class Main {
    /**//from   w  w  w  .j  a v a2 s  .c o  m
     * Gets a scaled instance of the source image.
     * Uses Graphics2D for scaling.
     * @param img
     * @param destw Target width, -1 if width should be in correct aspect ratio to target height.
     * @param desth Target height, -1 if height should be in correct aspect ratio to target width.
     * @param hint See RenderingHints.VALUE_INTERPOLATION_XXX
     * @return
     */
    public static BufferedImage getScaledInstance(BufferedImage img,
            int destw, int desth, Object hint) {
        Dimension d = getScaledSize(img.getWidth(), img.getHeight(), destw,
                desth);

        BufferedImage bimg = new BufferedImage(d.width, d.height,
                BufferedImage.TYPE_INT_ARGB);
        Graphics2D g2d = bimg.createGraphics();
        g2d.setRenderingHint(RenderingHints.KEY_INTERPOLATION, hint);
        g2d.drawImage(img, 0, 0, d.width, d.height, null);
        g2d.dispose();

        return (bimg);
    }

    /**
     * Calculates the scaled size.
     * @param ow
     * @param oh
     * @param tw
     * @param th
     * @return
     */
    private static Dimension getScaledSize(int ow, int oh, int tw, int th) {
        if ((tw > -1 && th > -1)) {
            return new Dimension(tw, th);
        } else if (tw < 0 && th < 0) {
            return new Dimension(ow, oh);
        }

        float fAspect = (float) ow / (float) oh;

        if (tw == -1) {
            // change width
            tw = (int) (th * fAspect);
        } else if (th == -1) {
            // change height
            th = (int) (tw / fAspect);
        }

        return new Dimension(tw, th);
    }
}

Related Tutorials