2010年4月5日星期一

利用 Java 旋轉圖片 (Use Java to rotate an image)

import java.awt.image.BufferedImage;
import java.awt.Graphics2D;
import java.awt.Color;
import java.awt.geom.AffineTransform;

public static BufferedImage rotate(BufferedImage source, double degrees, int x, int y, Color color, boolean resizable){
    double radians = Math.toRadians((degrees % 360.0 + 360.0) % 360.0);
    int width = source.getWidth();
    int height = source.getHeight();
    double rx = x;
    double ry = y;
    int cx = 0;
    int cy = 0;
    if (resizable){
        double dwidth = Math.abs(source.getWidth() * Math.cos(radians)) + Math.abs(source.getHeight() * Math.sin(radians));
        double dheight = Math.abs(source.getWidth() * Math.sin(radians)) + Math.abs(source.getHeight() * Math.cos(radians));
        width = (int)Math.round(dwidth);
        height = (int)Math.round(dheight);
        rx = dwidth / 2;
        ry = dheight / 2;
        cx = (int)Math.round((dwidth - source.getWidth()) / 2);
        cy = (int)Math.round((dheight - source.getHeight()) / 2);
    }
    BufferedImage out = new BufferedImage(width, height, source.getType());
    Graphics2D g2d = out.createGraphics();
    AffineTransform at = (AffineTransform) (g2d.getTransform().clone());
    at.rotate(radians, rx, ry);
    g2d.setTransform(at);
    g2d.drawImage(source, cx, cy, color, null);
    g2d.dispose();
    return out;
}

public static BufferedImage rotate(BufferedImage source, double degrees){
    return rotate(source, degrees, -1, -1, Color.WHITE, true);
}

修改前
before
apple.jpg

以 rotate(source, 45.0, 0, 0, Color.RED, false) 修改後
edit with rotate(source, 45.0, 0, 0, Color.RED, false)
apple2.jpg

以 rotate(source, -45.0) 修改後
edit width rotate(source, -45.0)
apple3.jpg

沒有留言 :

發佈留言