I know how to crop a raster by providing coordinates in a CRS:

Envelope envelope2D = new ReferencedEnvelope(envelopeStartX, envelopeEndX, envelopeStartY, envelopeEndY, obj.targetCRS);

GridCoverage2D tile = (GridCoverage2D) ops.crop(obj.coverage, envelope2D);

How do I crop by providing raster indices (ranging from 0..height, 0..width) instead of coordinates in a CRS?


You simply need to convert the corners of your rectangle to an envelope in the required CRS. You can then clip it as normal. The main thing to remember when doing this is that the Rectangle will have it's origin in the top left hand corner.

public GridCoverage2D clip(GridCoverage2D coverage, Rectangle r) {

    ReferencedEnvelope envelope = new ReferencedEnvelope(coverage.getCoordinateReferenceSystem());
    GridGeometry2D grid = coverage.getGridGeometry();
    GridEnvelope2D genv = new GridEnvelope2D(r);
    try {
      Envelope2D e = grid.gridToWorld(genv);
    } catch (TransformException e) {
      // TODO Auto-generated catch block
    return clip(coverage, envelope);

  public GridCoverage2D clip(GridCoverage2D coverage, ReferencedEnvelope envelope) {
    CoverageProcessor processor = CoverageProcessor.getInstance();

    // An example of manually creating the operation and parameters we want
    final ParameterValueGroup param = processor.getOperation("CoverageCrop").getParameters();

    return (GridCoverage2D) processor.doOperation(param);


So with this image as input the above code with a rectangle of Rectangle(0, 0, 250, 600)

enter image description here

will give this result (with ramp reversed to help you spot it):

enter image description here

|improve this answer|||||
  • if you provide Rectangle(0, 0, 250, 600) why do you get indents at the left and top of the resulting image? – Antonio Jul 4 '17 at 14:32
  • what indents do you mean? I think that's an artefact of the screen capture – Ian Turton Jul 4 '17 at 16:33

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.