Rescale an image based on scale factors for width and height. - Java 2D Graphics

Java examples for 2D Graphics:BufferedImage Scale

Description

Rescale an image based on scale factors for width and height.

Demo Code


//package com.java2s;

import java.awt.Graphics2D;

import java.awt.RenderingHints;

import java.awt.geom.AffineTransform;

import java.awt.image.BufferedImage;

public class Main {
    /**//  w  w  w.j  a  v  a 2s.  c om
     * Rescale an image based on scale factors for width and height.
     *
     * @param in - original buffered image.
     * @param dx - multiplier for the width (x direction)
     * @param dy - multiplier for the height (y direction)
     * @return - scaled buffered image
     */
    public static BufferedImage rescaleFractional(BufferedImage in,
            double dx, double dy) {
        int width = (int) (in.getWidth() * dx);
        int height = (int) (in.getHeight() * dy);
        BufferedImage newImage = new BufferedImage(width, height,
                BufferedImage.TYPE_INT_ARGB);

        Graphics2D g2 = newImage.createGraphics();
        AffineTransform at = AffineTransform.getScaleInstance(dx, dy);
        g2.setRenderingHint(RenderingHints.KEY_INTERPOLATION,
                RenderingHints.VALUE_INTERPOLATION_BICUBIC);
        g2.setRenderingHint(RenderingHints.KEY_ALPHA_INTERPOLATION,
                RenderingHints.VALUE_ALPHA_INTERPOLATION_QUALITY);
        g2.setRenderingHint(RenderingHints.KEY_RENDERING,
                RenderingHints.VALUE_RENDER_QUALITY);
        g2.drawRenderedImage(in, at);
        return newImage;
    }
}

Related Tutorials