import java.awt.Dimension;
import java.awt.Rectangle;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
public class ImageExpert {
public static void cropImage(String location, String x, String y, String h, String w){
try {
BufferedImage img = ImageIO.read(new File(location));
Dimension size = new Dimension(Integer.valueOf(w), Integer.valueOf(h));
Rectangle clip = null;
if ((size.width + Integer.valueOf(x)) <= img.getWidth()
&& (size.height + Integer.valueOf(y)) <= img.getHeight()) {
clip = new Rectangle(size);
} else {
if ((size.width + Integer.valueOf(x)) > img.getWidth()){
size.width = img.getWidth() - Integer.valueOf(x);
}
if ((size.height + Integer.valueOf(y)) > img.getHeight()){
size.height = img.getHeight() - Integer.valueOf(y);
}
clip = new Rectangle(size);
}
clip.x = Integer.valueOf(x);
clip.y = Integer.valueOf(y);
BufferedImage clipped = img.getSubimage(clip.x, clip.y, clip.height, clip.width);
File outputfile = new File(location);
ImageIO.write(clipped, getImageType(location), outputfile);
} catch (IOException e) {
e.printStackTrace();
}
}
private static String getImageType(String locationOrName){
return locationOrName.substring((locationOrName.lastIndexOf(".")+1));
}
}
2014年6月24日 星期二
【Java】圖像裁切
呼叫 ImageExpert 的 cropImage method
傳入圖片的所在路徑,以及要裁切位置的 x 與 y 軸,和要裁切的長度與高度
訂閱:
張貼留言 (Atom)
沒有留言:
張貼留言