2010-04-02

利用 Java 剪裁圖像的指定範圍 (Use Java to cut a rectangle of area from an image)

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

public static BufferedImage cut(BufferedImage source, int x, int y, int width, int height, int cx, int cy, Color color){
    BufferedImage out = new BufferedImage(width, height, source.getType());
    Graphics2D g2d = out.createGraphics();
    g2d.setColor(color);
    g2d.fillRect(0, 0, width, height);
    x -= cx;
    y -= cy;
    g2d.drawImage(source, 0, 0, width, height, x, y, x + width, y + height, null);
    g2d.dispose();
    return out;
}

public static BufferedImage cut(BufferedImage source, int x, int y, int width, int height){
    return cut(source, x, y, width, height, 0, 0, Color.WHITE);
}

修改前
before
apple.jpg

以 cut(source, 0, 0, 200, 200) 修改後
edit with cut(source, 0, 0, 200, 200)
apple2.jpg

以 cut(in, -100, 0, 200, 200) 修改後
edit with cut(in, -100, 0, 200, 200
apple3.jpg

以 cut(in, 150, 150, 200, 200, 100, 100, Color.WHITE) 修改後
edit with cut(in, 150, 150, 200, 200, 100, 100, Color.WHITE)
apple4.jpg

沒有留言 :

張貼留言