使用JAI切割TIF圖片
public void tifcut() throws FileNotFoundException, IOException {
//tif檔,存檔位置
StringBuilder tifPath = new StringBuilder();
//分割檔,存檔位置
StringBuilder savetifPath = new StringBuilder();
//如果存檔位置資料夾未建立,建立資料夾
if (!(new File(savetifPath.toString())).isDirectory()) {
(new File(savetifPath.toString())).mkdirs();
}
FileSeekableStream stream = new FileSeekableStream(tifPath.toString());
PlanarImage in = JAI.create("stream", stream);
int destWidth = in.getWidth(); //切割寬度
int destHeight = 1600 * 1024 * 8 / in.getHeight() / 2; //切割高度
int rows; //切割縱數量
//計算切片的縱向數量
if (in.getHeight() % destHeight == 0) {
rows = in.getHeight() / destHeight;
} else {
rows = (int) Math.floor(in.getHeight() / destHeight) + 1;
}
String Path = savetifPath.delete(savetifPath.length() - 4, savetifPath.length()).toString();
for (int i = 0; i < rows; i++) {
ParameterBlock pb = (new ParameterBlock());
pb.addSource(in);
if ((i + 1) * destHeight < in.getHeight()) {
pb.add(0f);//切割起始位置 x
pb.add((float) (i * destHeight));//切割起始位置 y
pb.add((float) destWidth);//切割寬度
pb.add((float) destHeight);//切割高度
} else {
pb.add(0f);
pb.add((float) (i * destHeight));
pb.add((float) destWidth);
pb.add((float) (in.getHeight() - i * destHeight));
}
String cutPath = Path + "_" + i + ".tif";
PlanarImage out = JAI.create("crop", pb, null);
OutputStream os = new FileOutputStream(cutPath);
TIFFEncodeParam param = new TIFFEncodeParam();
ImageEncoder enc = ImageCodec.createImageEncoder("tiff", os, param);
enc.encode(out);
os.close();
}
stream.close();
}