切割圖片

/**

* 圖片切割

*

* @param srcImageFile 圖片來源

* @param descDir 切割後儲存位置

* @param destWidth 切割寬度

* @param destHeight 切割高度

*/

public static void cut(String srcImageFile, String descDir, int destWidth, int destHeight) {

try {

Image img;

ImageFilter cropFilter;

//讀取圖片來源

BufferedImage bi = ImageIO.read(new File(srcImageFile));

int srcWidth = bi.getHeight();//圖片原始寬度

int srcHeight = bi.getWidth();//圖片原始高度

if (srcWidth > destWidth && srcHeight > destHeight) {

Image image = bi.getScaledInstance(srcWidth, srcHeight, Image.SCALE_DEFAULT);

destWidth = 200;//切割寬度

destHeight = 150;//切割高度

int cols = 0;//切割橫向數量

int rows = 0;//切割縱向數量

//計算切割的橫向和縱向數量

if (srcWidth % destWidth == 0) {

cols = srcWidth / destWidth;

} else {

cols = (int) Math.floor(srcWidth / destWidth) + 1;

}

if (srcHeight % destHeight == 0) {

rows = srcHeight / destHeight;

} else {

rows = (int) Math.floor(srcHeight / destHeight) + 1;

}

//循環建立切割

for (int i = 0; i < rows; i++) {

for (int j = 0; j < cols; j++) {

//四個參數分別為圖片的起點坐標和寬高

//即:CropImageFilter(int x, int y, int width, int height)

cropFilter = new CropImageFilter(j * 200, i * 150, destWidth, destHeight);

img = Toolkit.getDefaultToolkit().createImage(new FilteredImageSource(image.getSource(), cropFilter));

BufferedImage tag = new BufferedImage(destWidth, destHeight, BufferedImage.TYPE_INT_RGB);

Graphics g = tag.getGraphics();

g.drawImage(img, 0, 0, null);//繪制縮小後圖片

g.dispose();

//輸出圖片

ImageIO.write(tag, "JPEG", new File(descDir + "pre_map_" + i + "_" + j + ".jpg"));

}

}

}

} catch (Exception e) {

e.printStackTrace();

}

}