if (target.getDimension() == 2 && sourceCRS.getCoordinateSystem().getDimension() != 2) {
reducedCRS = CoverageUtilities.getCRS2D(source);
} else {
reducedCRS = sourceCRS;
}
GridGeometry gridGeometry = source.getGridGeometry();
if (targetCRS == null || CRS.equalsIgnoreMetadata(reducedCRS, targetCRS)) {
/*
* Same CRS (or unknown target CRS, which we treat as same), so we will keep the same
* "gridToCRS" transform. Basically the result will be the same as if we did a crop,
* except that we need to take in account a change from nD to 2D.
*/
final MathTransform gridToCRS;
if (reducedCRS == sourceCRS) {
gridToCRS = gridGeometry.getGridToCRS();
} else {
gridToCRS = GridGeometry2D.wrap(gridGeometry).getGridToCRS2D();
}
gridGeometry = new GridGeometry2D(PixelInCell.CELL_CENTER, gridToCRS, target, null);
} else {
/*
* Different CRS. We need to infer an image size, which may be the same than the
* original size or something smaller if the envelope is a subarea. We process by
* transforming the target envelope to the source CRS and compute a new grid geometry
* with that envelope. The grid range of that grid geometry is the new image size.
* Note that failure to transform the envelope is non-fatal (we will assume that the
* target image should have the same size). Then create again a new grid geometry,
* this time with the target envelope.
*/
GridEnvelope gridRange;
try {
final GeneralEnvelope transformed;
transformed = CRS.transform(CRS.getCoordinateOperationFactory(true)
.createOperation(targetCRS, reducedCRS), target);
final Envelope reduced;
final MathTransform gridToCRS;
if (reducedCRS == sourceCRS) {
reduced = source.getEnvelope();
gridToCRS = gridGeometry.getGridToCRS();
} else {
reduced = CoverageUtilities.getEnvelope2D(source);
gridToCRS = GridGeometry2D.wrap(gridGeometry).getGridToCRS2D();
}
transformed.intersect(reduced);
gridGeometry = new GridGeometry2D(PixelInCell.CELL_CENTER, gridToCRS, transformed, null);
} catch (FactoryException exception) {
recoverableException("resample", exception);
} catch (TransformException exception) {
recoverableException("resample", exception);
// Will use the grid range from the original geometry,
// which will result in keeping the same image size.
}
gridRange = gridGeometry.getGridRange();
gridGeometry = new GridGeometry2D(gridRange, target);
}
return gridGeometry;
}