java.awt.Graphics2D 图片缩放

关键字:java image thumbnail google

粗略demo:

import java.awt.Graphics2D;
import java.awt.GraphicsConfiguration;
import java.awt.GraphicsDevice;
import java.awt.GraphicsEnvironment;
import java.awt.geom.AffineTransform;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;

import javax.imageio.ImageIO;

import org.junit.Test;

public class ImageUtils {


    @Test
    public void test1() throws IOException {
        File file = new File("E:\\1.png");

        ImageUtils.scale(file, 0.1, new File("E:\\2.jpg"));
        ImageUtils.thumbnail(file, 100, new File("E:\\3.jpg"));
    }

    /**
     * 按比例缩放
     * 
     * @param rawImage
     * @param ratio
     * @param saltImage
     * 
     * @throws IOException
     * */
    public static void scale(File rawImage, double ratio, File saltImage) throws IOException {
        BufferedImage rawBufferedImage = ImageIO.read(rawImage);
        int width = (int) (rawBufferedImage.getWidth() * ratio);
        int height = (int) (rawBufferedImage.getHeight() * ratio);
        BufferedImage bi = getCompatibleImage(width, height);
        Graphics2D g2d = bi.createGraphics();
        double xScale = (double) width / rawBufferedImage.getWidth();
        double yScale = (double) height / rawBufferedImage.getHeight();
        AffineTransform at = AffineTransform.getScaleInstance(xScale, yScale);
        g2d.drawRenderedImage(rawBufferedImage, at);
        g2d.dispose();
        ImageIO.write(bi, "jpg", saltImage);
    }

    /**
     * 按比例缩放至【最大边 = 指定pix】
     * 
     * @param rawImage
     * @param pixel
     * @param saltImage
     * 
     * @throws IOException
     * */
    public static void thumbnail(File rawImage, int pixel, File saltImage) throws IOException {
        BufferedImage source = ImageIO.read(rawImage);
        int width = source.getWidth();
        int height = source.getHeight();

        int l = width > height ? width : height;

        double ratio = (pixel * 1.0) / l;

        int w = (int) (width * ratio);
        int h = (int) (height * ratio);

        BufferedImage bi = getCompatibleImage(w, h);
        Graphics2D g2d = bi.createGraphics();
        double xScale = (double) w / width;
        double yScale = (double) h / height;
        AffineTransform at = AffineTransform.getScaleInstance(xScale, yScale);
        g2d.drawRenderedImage(source, at);
        g2d.dispose();
        ImageIO.write(bi, "jpg", saltImage);
    }

    private static BufferedImage getCompatibleImage(int w, int h) {
        GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
        GraphicsDevice gd = ge.getDefaultScreenDevice();
        GraphicsConfiguration gc = gd.getDefaultConfiguration();
        BufferedImage image = gc.createCompatibleImage(w, h);
        return image;
    }

}