scale BufferedImage Image To Width - Java 2D Graphics

Java examples for 2D Graphics:BufferedImage Scale

Description

scale BufferedImage Image To Width

Demo Code

import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.RenderingHints;
import java.awt.geom.AffineTransform;
import java.awt.image.BufferedImage;
import java.awt.image.RescaleOp;
import javax.swing.JComponent;

public class Main{
    public static BufferedImage scaleImageToWidth(BufferedImage image,
            int width) {
        BufferedImage newImage = new BufferedImage(width, image.getHeight()
                * width / image.getWidth(), BufferedImage.TYPE_INT_ARGB);
        Graphics2D graph = newImage.createGraphics();
        GraphicsUtil.enableAntialiasing(graph);
        graph.drawImage(image, 0, 0, newImage.getWidth(),
                newImage.getHeight(), null);
        return newImage;
    }// www  .ja v  a 2s.c o  m
    public static void enableAntialiasing(Graphics g) {
        if (g instanceof Graphics2D) {
            Graphics2D g2 = (Graphics2D) g;
            g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
                    RenderingHints.VALUE_ANTIALIAS_ON);
        } else {
            throw new RuntimeException("Need a graphics2D object");
        }
    }
}

Related Tutorials