Thanks for Arturo Mendes's answer,but I barely know GDAL and prefer use Geotools. If someone is like me,you can refer to this question:How to crop an image based on a shapefile using GeoTools
and the code,the key code is line 213-218,you can compare it to the code of the above question
the follow code can achieve the purpose
/***
*Crop the GeoTiff base on geometric range
* @param tifURL
* @param tfwURL
* @param range geometric range
* @return GridCoverage of cropped tiff file
* @throws Exception
*/
public static GridCoverage cropGeoTiff(String tifURL, String tfwURL, Geometry range) throws Exception {
//tiff
File tiff = new File(tifURL);
//twf
File twf = new File(tfwURL);
TIFFImageReader tiffImageReader =
(it.geosolutions.imageioimpl.plugins.tiff.TIFFImageReader)
new TIFFImageReaderSpi().createReaderInstance();
tiffImageReader.setInput(ImageIO.createImageInputStream(tiff));
BufferedImage image = tiffImageReader.read(0);
tiffImageReader.dispose();
MathTransform transform = new WorldFileReader(twf).getTransform();
GridCoverage2D coverage2D =
CoverageFactoryFinder.getGridCoverageFactory(null)
.create(
"coverage",
image,
new GridGeometry2D(
new GridEnvelope2D(
PlanarImage.wrapRenderedImage(image).getBounds()),
transform,
DefaultGeographicCRS.WGS84),
new GridSampleDimension[]{new GridSampleDimension("coverage")},
null,
null);
GridCoverage clippedCoverage = null;
List<Geometry> geometryList = new ArrayList<Geometry>();
geometryList.add(range);
if (geometryList.size() > 0) {
CoverageProcessor processor = new CoverageProcessor();
//define the crop operation
ParameterValueGroup params = processor.getOperation("CoverageCrop")
.getParameters();
//the GridCoverage which you want to crop
params.parameter("Source").setValue(coverage2D);
GeometryFactory factory = JTSFactoryFinder.getGeometryFactory(null);
Geometry[] a = geometryList.toArray(new Geometry[0]);
GeometryCollection c = new GeometryCollection(a, factory);
//params.parameter("ENVELOPE").setValue(bounds);
params.parameter("ROI").setValue(c);
params.parameter("ForceMosaic").setValue(true);
clippedCoverage = (GridCoverage) processor.doOperation(params);
return clippedCoverage;
}
return null;
}