This is an automated email from the ASF dual-hosted git repository.

asf-gitbox-commits pushed a commit to branch geoapi-4.0
in repository https://gitbox.apache.org/repos/asf/sis.git


The following commit(s) were added to refs/heads/geoapi-4.0 by this push:
     new 79037ce830 Initial support of `AggregatedImage` as an alternative to 
`ResampledImage` for doing resampling using a `MathTransform` from source to 
target image instead of the opposite. It allows to get a result when a 
transform is difficult to inverse, and is also helpful when the resampling 
needs to conserve the total energy.
79037ce830 is described below

commit 79037ce83053503103661469e6fa70950c6e7bbe
Author: Martin Desruisseaux <[email protected]>
AuthorDate: Thu Nov 12 19:16:14 2026 +0100

    Initial support of `AggregatedImage` as an alternative to `ResampledImage`
    for doing resampling using a `MathTransform` from source to target image 
instead of the opposite.
    It allows to get a result when a transform is difficult to inverse, and is 
also helpful when the
    resampling needs to conserve the total energy.
---
 .../sis/coverage/grid/GridCoverageBuilder.java     |  59 +--
 .../apache/sis/coverage/grid/ImageRenderer.java    |  11 +-
 .../main/org/apache/sis/image/AggregatedImage.java | 568 +++++++++++++++++++++
 .../org/apache/sis/image/BandAggregateImage.java   |   4 +-
 .../main/org/apache/sis/image/ComputedImage.java   |  19 +-
 .../main/org/apache/sis/image/ImageCombiner.java   |   4 +-
 .../main/org/apache/sis/image/PixelIterator.java   |  12 +-
 .../main/org/apache/sis/image/PlanarImage.java     |   7 +-
 .../sis/image/PositionalConsistencyImage.java      |   2 +-
 .../main/org/apache/sis/image/ResampledImage.java  |  49 +-
 .../sis/image/internal/shared/TiledImage.java      | 110 ++--
 .../image/internal/shared/WritableTiledImage.java  |  72 ++-
 .../main/org/apache/sis/image/package-info.java    |  13 +-
 .../coverage/grid/ResampledGridCoverageTest.java   |  13 +-
 .../org/apache/sis/image/InterpolationTest.java    |  10 +-
 .../test/org/apache/sis/image/MaskedImageTest.java |  14 +-
 .../test/org/apache/sis/image/TiledImageMock.java  |   5 +-
 .../operation/transform/MathTransforms.java        |  18 +-
 .../sis/storage/tiling/TiledGridCoverage.java      |  15 +-
 19 files changed, 842 insertions(+), 163 deletions(-)

diff --git 
a/endorsed/src/org.apache.sis.feature/main/org/apache/sis/coverage/grid/GridCoverageBuilder.java
 
b/endorsed/src/org.apache.sis.feature/main/org/apache/sis/coverage/grid/GridCoverageBuilder.java
index 86fc875f39..ef0cde8b41 100644
--- 
a/endorsed/src/org.apache.sis.feature/main/org/apache/sis/coverage/grid/GridCoverageBuilder.java
+++ 
b/endorsed/src/org.apache.sis.feature/main/org/apache/sis/coverage/grid/GridCoverageBuilder.java
@@ -94,9 +94,9 @@ import org.apache.sis.pending.jdk.JDK18;
  *     }
  * }
  *
- * <h2>Limitations</h2>
+ * <p><b>Limitation:</b>
  * Current implementation creates only two-dimensional coverages.
- * A future version may extend this builder API for creating 
<var>n</var>-dimensional coverages.
+ * A future version may extend this builder API for creating 
<var>n</var>-dimensional coverages.</p>
  *
  * @author  Johann Sorel (Geomatys)
  * @author  Martin Desruisseaux (Geomatys)
@@ -251,7 +251,7 @@ public class GridCoverageBuilder {
      * (i.e. the matrix representation of the affine transform will be 
diagonal,
      * ignoring the translation column).
      *
-     * <h4>Axis directions</h4>
+     * <h4>Default axis directions of coverage created from an envelope</h4>
      * By default grid indices increase in the same direction as domain 
coordinates.
      * When applied to images with pixels located by (<var>column</var>, 
<var>row</var>) indices,
      * it means that by default row indices in the image are increasing toward 
up if the <var>y</var>
@@ -264,17 +264,16 @@ public class GridCoverageBuilder {
      * If more sophisticated operations is desired (for example a rotation),
      * then {@link #setDomain(GridGeometry)} should be used instead of this 
method.</p>
      *
-     * <h5>Design note</h5>
+     * <h5>Implementation note</h5>
      * {@code GridCoverageBuilder} does not flip the <var>y</var> axis by 
default because not all
      * file formats have row indices increasing toward down. A counter-example 
is the netCDF format.
      * Even if we consider that the majority of images have <var>y</var> axis 
flipped, things become
      * less obvious when considering data in more than two dimensions. Having 
the same default policy
      * (no flipping) for all dimensions make problem analysis easier.
      *
-     * <h4>Default implementation</h4>
-     * The default implementation creates a new {@link GridGeometry} from the 
given envelope
+     * <p>The default implementation creates a new {@link GridGeometry} from 
the given envelope
      * then invokes {@link #setDomain(GridGeometry)}. Subclasses can override 
that later method
-     * as a single overriding point for all domain settings.
+     * as a single overriding point for all domain settings.</p>
      *
      * @param  domain  envelope of the coverage domain together with its CRS,
      *                 or {@code null} for removing previous domain setting.
@@ -567,22 +566,6 @@ public class GridCoverageBuilder {
         return this;
     }
 
-    /**
-     * Creates a color model for the given sample model.
-     *
-     * @param  sm     the sample model.
-     * @param  bands  {@link #ranges} if non-null, or a default non-null value 
otherwise.
-     * @return the color model.
-     */
-    private ColorModel createColorModel(final SampleModel sm, final List<? 
extends SampleDimension> bands) {
-        final var colorizer = new 
ColorScaleBuilder(ColorScaleBuilder.GRAYSCALE, null, false);
-        if (colorizer.initialize(sm, bands.get(visibleBand)) || 
colorizer.initialize(sm, visibleBand)) {
-            return colorizer.createColorModel(sm, bands.size(), visibleBand);
-        } else {
-            return ColorScaleBuilder.NULL_COLOR_MODEL;
-        }
-    }
-
     /**
      * Creates an image from the given rasters.
      * The first tile in the given array must be the one located at the 
minimal tile indices.
@@ -591,13 +574,24 @@ public class GridCoverageBuilder {
      * <p>This method tries to create the most standard objects when possible: 
preferably a
      * {@link BufferedImage} from Java2D, otherwise a {@link TiledImage} from 
<abbr>SIS</abbr>.</p>
      *
-     * @param  colors  the color model, or {@code null}.
-     * @param  width   the image width in pixels.
-     * @param  height  the image height in pixels.
+     * @param  sm      the sample model.
+     * @param  bands   {@link #ranges} if non-null, or a default non-null 
value otherwise.
+     * @param  bounds  the image width and height in pixels, together with the 
location of the first tile.
      * @param  tiles   the image tiles.
      * @return an image for the given rasters.
      */
-    private RenderedImage createImage(final ColorModel colors, final int 
width, final int height, final Raster... tiles) {
+    private RenderedImage createImage(final SampleModel sm,
+                                      final List<? extends SampleDimension> 
bands,
+                                      final Rectangle bounds,
+                                      final Raster... tiles)
+    {
+        final ColorModel colors;
+        final var colorizer = new 
ColorScaleBuilder(ColorScaleBuilder.GRAYSCALE, null, false);
+        if (colorizer.initialize(sm, bands.get(visibleBand)) || 
colorizer.initialize(sm, visibleBand)) {
+            colors = colorizer.createColorModel(sm, bands.size(), visibleBand);
+        } else {
+            colors = ColorScaleBuilder.NULL_COLOR_MODEL;
+        }
         if (colors != null && tiles.length == 1) {
             final Raster tile = tiles[0];
             if (tile instanceof WritableRaster && (tile.getMinX() | 
tile.getMinY()) == 0) {
@@ -605,9 +599,9 @@ public class GridCoverageBuilder {
             }
         }
         if (tiles instanceof WritableRaster[]) {
-            return new WritableTiledImage(properties, colors, width, height, 
0, 0, (WritableRaster[]) tiles);
+            return new WritableTiledImage(properties, colors, sm, bounds, 
null, (WritableRaster[]) tiles);
         } else {
-            return new TiledImage(properties, colors, width, height, 0, 0, 
tiles);
+            return new TiledImage(properties, colors, sm, bounds, null, tiles);
         }
     }
 
@@ -649,8 +643,9 @@ public class GridCoverageBuilder {
             location.y = ymin + (i / numXTiles) * tileHeight;
             tiles[i] = WritableRaster.createWritableRaster(sm, location);
         }
-        final var data = (WritableRenderedImage) 
createImage(createColorModel(sm, bands), width, height, tiles);
-        final WritablePixelIterator i = new 
WritablePixelIterator.Builder().createWritable(data);
+        final var bounds = new Rectangle(xmin, ymin, width, height);
+        final var data = (WritableRenderedImage) createImage(sm, bands, 
bounds, tiles);
+        final WritablePixelIterator i = WritablePixelIterator.create(data);
         if (calcAsDoubles != null) {
             i.setRemainingPixels(calcAsDoubles);
         } else {
@@ -693,7 +688,7 @@ public class GridCoverageBuilder {
                      * and fallback on TiledImage only if the BufferedImage 
cannot be created.
                      */
                     properties.put(PlanarImage.SAMPLE_DIMENSIONS_KEY, 
bands.toArray(SampleDimension[]::new));
-                    data = createImage(createColorModel(sm, bands), 
raster.getWidth(), raster.getHeight(), raster);
+                    data = createImage(sm, bands, raster.getBounds(), raster);
                     properties.remove(PlanarImage.SAMPLE_DIMENSIONS_KEY);
                 } else {
                     /*
diff --git 
a/endorsed/src/org.apache.sis.feature/main/org/apache/sis/coverage/grid/ImageRenderer.java
 
b/endorsed/src/org.apache.sis.feature/main/org/apache/sis/coverage/grid/ImageRenderer.java
index 864d7b41de..d0a02a46d6 100644
--- 
a/endorsed/src/org.apache.sis.feature/main/org/apache/sis/coverage/grid/ImageRenderer.java
+++ 
b/endorsed/src/org.apache.sis.feature/main/org/apache/sis/coverage/grid/ImageRenderer.java
@@ -79,7 +79,7 @@ import org.opengis.coordinate.MismatchedDimensionException;
  * computes automatically the offsets from that position to the position of 
the first value included
  * in the {@code sliceExtent} given to the constructor.</p>
  *
- * <h2>Usage example</h2>
+ * <p><b>Usage example:</b></p>
  * {@snippet lang="java" :
  *     class MyResource extends GridCoverage {
  *         @Override
@@ -95,9 +95,9 @@ import org.opengis.coordinate.MismatchedDimensionException;
  *     }
  *     }
  *
- * <h2>Limitations</h2>
+ * <p><b>Limitation:</b>
  * Current implementation constructs only images made of a single tile.
- * Support for tiled images will be added in a future version.
+ * Support for tiled images will be added in a future version.</p>
  *
  * @author  Martin Desruisseaux (Geomatys)
  * @version 1.7
@@ -795,10 +795,11 @@ public class ImageRenderer {
             return new WritableUntiledImage(cm, wr, false, 
properties).setGridGeometry(imageGeometry, supplier);
         }
         properties.putIfAbsent(GRID_GEOMETRY_KEY, (supplier != null) ? new 
DeferredProperty(supplier) : imageGeometry);
+        final var bounds = new Rectangle(imageX, imageY, width, height);
         if (wr != null) {
-            return new WritableTiledImage(properties, cm, width, height, 0, 0, 
wr);
+            return new WritableTiledImage(properties, cm, sm, bounds, null, 
wr);
         } else {
-            return new TiledImage(properties, cm, width, height, 0, 0, raster);
+            return new TiledImage(properties, cm, sm, bounds, null, raster);
         }
     }
 }
diff --git 
a/endorsed/src/org.apache.sis.feature/main/org/apache/sis/image/AggregatedImage.java
 
b/endorsed/src/org.apache.sis.feature/main/org/apache/sis/image/AggregatedImage.java
new file mode 100644
index 0000000000..d92a67dea9
--- /dev/null
+++ 
b/endorsed/src/org.apache.sis.feature/main/org/apache/sis/image/AggregatedImage.java
@@ -0,0 +1,568 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.sis.image;
+
+import java.util.Map;
+import java.util.Vector;
+import java.util.Arrays;
+import java.util.Objects;
+import java.util.ConcurrentModificationException;
+import java.util.concurrent.RecursiveTask;
+import java.awt.Point;
+import java.awt.Rectangle;
+import java.awt.image.ColorModel;
+import java.awt.image.SampleModel;
+import java.awt.image.Raster;
+import java.awt.image.WritableRaster;
+import java.awt.image.RasterFormatException;
+import java.awt.image.RenderedImage;
+import java.awt.image.ImagingOpException;
+import org.apache.sis.geometry.Shapes2D;
+import org.opengis.referencing.operation.MathTransform;
+import org.opengis.referencing.operation.TransformException;
+import org.apache.sis.referencing.operation.transform.MathTransforms;
+import org.apache.sis.image.internal.shared.WritableTiledImage;
+import org.apache.sis.image.internal.shared.ImageUtilities;
+import org.apache.sis.coverage.grid.PixelInCell;
+import org.apache.sis.pending.jdk.JDK18;
+import org.apache.sis.util.Exceptions;
+import org.apache.sis.util.ArgumentChecks;
+import org.apache.sis.util.resources.Errors;
+import org.apache.sis.util.collection.BackingStoreException;
+
+// Specific to the GeoAPI 3.1 and 4.0 branches:
+import org.opengis.coverage.grid.SequenceType;
+
+
+/**
+ * An image which is the result of aggregating the pixel values of other 
images.
+ * Aggregating is the action of computing the pixel values of this image from 
the
+ * values of overlapping pixels in source images.
+ * The aggregation can be performed by statistic methods such as weighted 
average.
+ * Each source image is associated with a {@link MathTransform} which converts 
pixel corner
+ * coordinates from the <em>source</em> image to pixel corner coordinates in 
<em>this</em> image.
+ *
+ * <p>This image class can be used as an alternative to {@link ResampledImage}
+ * when an aggregation method is desired instead of an interpolation method.
+ * For example, weighted averages are preferred to bilinear interpolations when
+ * pixel values are proportional to physical energy and the total energy needs 
to be preserved.
+ * {@code AggregatedImage} can also be used as a fallback when {@code 
ResampledImage} fails to
+ * resample an image because of a {@link TransformException}.
+ * Since these two image classes use {@link MathTransform} in opposite 
directions,
+ * an exception thrown in one direction may be absent in the opposite 
direction.</p>
+ *
+ * <p>Contrary to {@link ComputedImage}, this image computes all tiles 
immediately when one tile is requested.
+ * For very large images, {@link ResampledImage} is preferred because it 
defers computation on a tile-by-tile
+ * basis instead of computing the whole image.</p>
+ *
+ * @author  Martin Desruisseaux (Geomatys)
+ * @version 1.8
+ *
+ * @since SIS 1.8
+ */
+public class AggregatedImage extends PlanarImage {
+    /**
+     * The images containing the pixels to aggregate in this image.
+     */
+    private final RenderedImage[] sources;
+
+    /**
+     * Conversions from pixel coordinates of <em>source</em> images to 
<em>this</em> image.
+     * The transforms map {@linkplain PixelInCell#CELL_CORNER pixel corners}.
+     */
+    private final MathTransform[] fromSources;
+
+    /**
+     * Domain of pixel coordinates in this image.
+     */
+    private final int minX, minY, width, height;
+
+    /**
+     * Index of the first tile. This is usually 0.
+     */
+    private final int minTileX, minTileY;
+
+    /**
+     * The sample model declared at construction time.
+     */
+    protected final SampleModel sampleModel;
+
+    /**
+     * The values to use if the source images provide no value.
+     */
+    private final double[] fillValues;
+
+    /**
+     * Number of bands in which some values will be aggregated.
+     * This is usually the number of bands given by {@link 
SampleModel#getNumBands()},
+     * but may be smaller if all source images have a smaller number of bands.
+     */
+    private final int effectiveNumBands;
+
+    /**
+     * Number of values per sample needed by the accumulator during the 
computation phase.
+     * For example we need two values for computing averages: the sum and the 
number of values in the sum.
+     */
+    private static final int NUM_ACCUMULATORS = 2;
+
+    /**
+     * Width and height of each chunk, in number of cells. Each cell contains 
many bands.
+     * The size of accumulator chunks does not need to be related to the size 
of image tiles.
+     * We prefer a relatively small chunk size in order to create small 
temporary arrays
+     * during {@link SourceScanner} execution.
+     */
+    private static final int CHUNK_SIZE = 32;
+
+    /**
+     * Number of chunks needed for covering all the surface of this image.
+     * The chunks are created only during the time when aggregation is 
performed.
+     */
+    private final int numChunks;
+
+    /**
+     * All tiles in a row-major fashion, created when first requested.
+     *
+     * @see #getTile(int, int)
+     */
+    private WritableRaster[] tiles;
+
+    /**
+     * Creates a new image which will aggregate the given images. The 
operation requires transforms
+     * (which can be non-linear) from the specified <em>source</em> images to 
<em>this</em> image.
+     * The transforms shall map {@linkplain PixelInCell#CELL_CORNER pixel 
corners}.
+     *
+     * <p>The given {@code sampleModel} determines the tile size and the 
target data type.
+     * This is often the same sample model as the ones used by the source 
images,
+     * but may also be different for forcing a different tile size or a 
different data type
+     * (for example, casting {@code float} values to {@code byte}s).
+     * If the specified sample model is not the same as the one used by the 
source images,
+     * then subclass should override {@link #getColorModel()} for returning a 
color model which is
+     * {@linkplain ColorModel#isCompatibleSampleModel(SampleModel) compatible 
with the sample model}.</p>
+     *
+     * @param  sources      the images to aggregate with their transforms from 
<em>source</em> to <em>this</em>.
+     * @param  sampleModel  the sample model for this aggregated image.
+     * @param  minTile      indices of the first tile ({@code minTileX}, 
{@code minTileY}), or {@code null} for (0,0).
+     * @param  bounds       domain of pixel coordinates of this aggregated 
image, or {@code null} for automatic.
+     * @param  fillValues   the values to use if the source images provide no 
value, or {@code null} for zeros.
+     * @throws TransformException if {@code bounds} is null and an error 
occurred while computing automatic bounds.
+     */
+    public AggregatedImage(final Map<RenderedImage, MathTransform> sources,
+                           final SampleModel sampleModel,
+                           final Point minTile,
+                           Rectangle bounds,
+                           double[] fillValues)
+            throws TransformException
+    {
+        final int numSources = sources.size();
+        this.sources     = new RenderedImage[numSources];
+        this.fromSources = new MathTransform[numSources];
+        this.sampleModel = Objects.requireNonNull(sampleModel);
+        final boolean computeBounds = (bounds == null);
+        int i = 0, numBands = 0;
+        for (final var entry : sources.entrySet()) {
+            final RenderedImage source = entry.getKey();
+            final MathTransform fromSource = entry.getValue();
+            ArgumentChecks.ensureNonNullElement("sources[#].key",   i, source);
+            ArgumentChecks.ensureNonNullElement("sources[#].value", i, 
fromSource);
+            ArgumentChecks.ensureDimensionsMatch("sources", BIDIMENSIONAL, 
BIDIMENSIONAL, fromSource);
+            this.fromSources[i] = fromSource;
+            this.sources[i++] = source;
+            numBands = Math.max(numBands, ImageUtilities.getNumBands(source));
+            if (computeBounds) {
+                final Rectangle boundsOfSource = 
ImageUtilities.getBounds(source);
+                Shapes2D.transform(MathTransforms.bidimensional(fromSource), 
boundsOfSource, boundsOfSource);
+                if (bounds == null) {
+                    bounds = boundsOfSource;
+                } else {
+                    bounds.add(boundsOfSource);
+                }
+            }
+        }
+        if (i != numSources) {
+            throw new ConcurrentModificationException();    // New entries 
added while we were iterating.
+        }
+        minX = bounds.x;
+        minY = bounds.y;
+        ArgumentChecks.ensureStrictlyPositive("width",  width  = bounds.width);
+        ArgumentChecks.ensureStrictlyPositive("height", height = 
bounds.height);
+        effectiveNumBands = Math.min(sampleModel.getNumBands(), numBands);
+        if (effectiveNumBands >= Integer.MAX_VALUE / (CHUNK_SIZE * CHUNK_SIZE 
* NUM_ACCUMULATORS)) {
+            throw new 
RasterFormatException(Errors.format(Errors.Keys.IllegalPropertyValue_2, 
"numBands", effectiveNumBands));
+        }
+        if (fillValues == null) {
+            fillValues = new double[effectiveNumBands];
+        } else {
+            fillValues = Arrays.copyOf(fillValues, effectiveNumBands);
+        }
+        this.fillValues = fillValues;
+        numChunks = Math.multiplyExact(numChunks(width), numChunks(height));
+        if (minTile != null) {
+            minTileX = minTile.x;
+            minTileY = minTile.y;
+        } else {
+            minTileX = 0;
+            minTileY = 0;
+        }
+    }
+
+    /**
+     * Returns the number of chunks for the given size.
+     *
+     * @param  size  number of cells.
+     * @return number of chunks needed for the given number of cells.
+     */
+    private static int numChunks(final int size) {
+        return JDK18.ceilDiv(size, CHUNK_SIZE);
+    }
+
+    /**
+     * Returns the immediate sources of image data for this image.
+     * This method returns all sources specified at construction time.
+     *
+     * @return the immediate sources.
+     */
+    @Override
+    @SuppressWarnings("UseOfObsoleteCollectionType")
+    public Vector<RenderedImage> getSources() {
+        return new Vector<>(Arrays.asList(sources));
+    }
+
+    /**
+     * Returns the color model of this aggregated image.
+     * The default implementation returns the color model of the first 
compatible source.
+     *
+     * @return the color model, or {@code null} if unspecified.
+     */
+    @Override
+    public ColorModel getColorModel() {
+        for (final RenderedImage source : sources) {
+            final ColorModel cm = source.getColorModel();
+            if (cm != null && cm.isCompatibleSampleModel(getSampleModel())) {
+                return cm;
+            }
+        }
+        return null;
+    }
+
+    /**
+     * Returns the sample model associated with this image.
+     * All rasters returned from this image will have this sample model.
+     *
+     * @return the sample model of this image.
+     */
+    @Override
+    public SampleModel getSampleModel() {
+        return sampleModel;
+    }
+
+    /**
+     * Returns the number of columns in this image.
+     * This is the {@link Rectangle#width} value of the {@code bounds} 
specified or inferred at construction time.
+     *
+     * @return number of columns in this image.
+     */
+    @Override
+    public final int getWidth() {
+        return width;
+    }
+
+    /**
+     * Returns the number of rows in this image.
+     * This is the {@link Rectangle#height} value of the {@code bounds} 
specified or inferred at construction time.
+     *
+     * @return number of rows in this image.
+     */
+    @Override
+    public final int getHeight() {
+        return height;
+    }
+
+    /**
+     * Returns the minimum <var>x</var> coordinate (inclusive) of this image.
+     * This is the {@link Rectangle#x} value of the {@code bounds} specified
+     * or inferred at construction time.
+     */
+    @Override
+    public final int getMinX() {
+        return minX;
+    }
+
+    /**
+     * Returns the minimum <var>y</var> coordinate (inclusive) of this image.
+     * This is the {@link Rectangle#y} value of the {@code bounds} specified
+     * or inferred at construction time.
+     */
+    @Override
+    public final int getMinY() {
+        return minY;
+    }
+
+    /**
+     * Returns the minimum tile index in the <var>x</var> direction. This is 
often 0.
+     */
+    @Override
+    public int getMinTileX() {
+        return minTileX;
+    }
+
+    /**
+     * Returns the minimum tile index in the <var>y</var> direction. This is 
often 0.
+     */
+    @Override
+    public final int getMinTileY() {
+        return minTileY;
+    }
+
+    /**
+     * Returns the width of tiles in this image.
+     *
+     * @return the width (in pixels) of all tiles in this image.
+     */
+    @Override
+    public int getTileWidth() {
+        return getSampleModel().getWidth();
+    }
+
+    /**
+     * Returns the height of tiles in this image.
+     *
+     * @return the height (in pixels) of all tiles in this image.
+     */
+    @Override
+    public int getTileHeight() {
+        return getSampleModel().getHeight();
+    }
+
+    /**
+     * Returns a tile of this image, computing it when needed.
+     *
+     * @param  tileX  the column index of the tile to get.
+     * @param  tileY  the row index of the tile to get.
+     * @return the tile at the given index (never null).
+     * @throws IndexOutOfBoundsException if a given tile index is out of 
bounds.
+     * @throws ImagingOpException if an error occurred while computing the 
image.
+     */
+    @Override
+    public synchronized Raster getTile(final int tileX, final int tileY) {
+        final int numXTiles = getNumXTiles();
+        final int numYTiles = getNumYTiles();
+        checkTileIndex("tileX", minTileX, numXTiles, tileX);
+        checkTileIndex("tileY", minTileY, numYTiles, tileY);
+        final int chunkCellStride = effectiveNumBands * NUM_ACCUMULATORS;
+        if (tiles == null) try {
+            // Execute the aggregation now, possibly using many threads.
+            final double[][] data = new SourceScanner().compute();
+            /*
+             * At this point, the calculatuon of all aggregated values is 
completed.
+             * Dispatch the results in the tiles of this image.
+             */
+            final int chunksPerImageRow = numChunks(width);
+            final var bounds = new Rectangle(CHUNK_SIZE, CHUNK_SIZE);
+            final var samples = new double[effectiveNumBands];
+            final var writable = new WritableTiledImage(
+                    null,           // Properties,  not needed for dispatching 
values.
+                    null,           // Color model, not needed for dispatching 
values.
+                    getSampleModel(),
+                    new Rectangle(minX, minY, width, height),
+                    new Point(minTileX, minTileY),
+                    tiles = new WritableRaster[numXTiles * numYTiles]);
+
+            for (int i=0; i<data.length; i++) {
+                final double[] tileData = data[i];
+                if (tileData != null) {
+                    bounds.y = (i / chunksPerImageRow) * CHUNK_SIZE + minX;
+                    bounds.x = (i % chunksPerImageRow) * CHUNK_SIZE + minY;
+                    try (WritablePixelIterator it = new PixelIterator.Builder()
+                                .setIteratorOrder(SequenceType.LINEAR)
+                                .setRegionOfInterest(bounds)
+                                .createWritable(writable))
+                    {
+                        // Should always be zero because the first chunck 
starts at the image corner, but check anyway.
+                        int valueIndex = ((it.lowerY - bounds.y)  * CHUNK_SIZE
+                                       +  (it.lowerX - bounds.x)) * 
chunkCellStride;
+                        final int toNextRow = (bounds.x + CHUNK_SIZE - 
it.upperX) * chunkCellStride;
+                        while (it.next()) {
+                            if (it.isBeginningOfNewRow()) {
+                                valueIndex += toNextRow;
+                            }
+                            for (int j=0; j < samples.length; j++) {
+                                // The two values counted by 
`NUM_ACCUMULATORS`.
+                                final double sum = tileData[valueIndex++];
+                                final double num = tileData[valueIndex++];
+                                samples[j] = (num != 0) ? sum/num : 
fillValues[j];
+                            }
+                            it.setPixel(samples);
+                        }
+                    }
+                }
+            }
+        } catch (ImagingOpException e) {
+            throw e;
+        } catch (Exception cause) {
+            final var e = new ImagingOpException(cause.getLocalizedMessage());
+            e.initCause(Exceptions.unwrap(cause));
+            throw e;
+        }
+        return tiles[(tileX - minTileX) + (tileY - minTileY) * numXTiles];
+    }
+
+    /**
+     * A task for aggregating the values of source images. This class is not 
thread safe.
+     * However, each {@code SourceScanner} instance can be subdivided into 
other instances
+     * working on a subset of the images and tiles. Each sub-task can be 
executed
+     * in a different thread and their results combined after task completion.
+     */
+    @SuppressWarnings("serial")     // Not intended to be serialized.
+    private final class SourceScanner extends RecursiveTask<double[][]> {
+        /**
+         * Index of the next source image to aggregate.
+         */
+        private int imageIndex;
+
+        /**
+         * Index after the last source image to aggregate.
+         */
+        private final int upperImageIndex;
+
+        /**
+         * Creates a new task initialized for aggregating all tiles of all 
images.
+         */
+        SourceScanner() {
+            upperImageIndex = sources.length;
+        }
+
+        /**
+         * Number of values in each chunk. This is the length of the arrays to 
create
+         * in the second dimension of {@link SourceScanner#compute()} return 
values.
+         */
+        private int accumulatorValuesPerChunk() {
+            return CHUNK_SIZE * CHUNK_SIZE * NUM_ACCUMULATORS * 
effectiveNumBands;
+        }
+
+        /**
+         * Iterates over the tiles of source images and aggregates their pixel 
values in a temporary array.
+         * The aggregation result is returned in separate arrays of aggregated 
values for each target tiles.
+         * The index in the first {@code double[][]} array dimension is the 
tile index (in the target image)
+         * with tiles arranged in a row-major fashion. The index in the second 
array dimension is the sample
+         * value index with <var>y</var> pixel coordinate varying slowest, 
then <var>x</var> pixel coordinate,
+         * then band index, then accumulator index for a total length of 
{@link #accumulatorValuesPerChunk()}.
+         *
+         * @return Result of the aggregation for each tile in the enclosing 
target image.
+         */
+        @Override
+        protected double[][] compute() {
+            final double[] imageOffset = {getMinX(), getMinY()};
+            final double[][] data = new double[numChunks][];
+            final double[] sourcePixelCorners = new double[BIDIMENSIONAL * 2]; 
 // Bounds of a single source pixel in target coordinates.
+            final int chunkValueStride = effectiveNumBands * NUM_ACCUMULATORS;
+            final int chunksPerImageRow = numChunks(getWidth());
+            while (imageIndex < upperImageIndex) {
+                final MathTransform fromSource = fromSources[imageIndex];
+                final RenderedImage source = sources[imageIndex];
+                final double[][] coordinates = new 
double[2][(source.getTileWidth() + 1) * BIDIMENSIONAL];
+                final int srcMinTileX = source.getMinTileX();
+                final int srcMinTileY = source.getMinTileY();
+                final int srcNumTileX = source.getNumXTiles();
+                final int srcNumTiles = Math.multiplyExact(srcNumTileX, 
source.getNumYTiles());
+                for (int srcTileIndex = 0; srcTileIndex < srcNumTiles; 
srcTileIndex++) try {
+                    /*
+                     * We will iterate over all pixels of a single tile of a 
source image.
+                     * For each pixel, the coordinates of the 4 corners will 
be transformed
+                     * to coordinates of a bounding box in the target image 
(conceptually,
+                     * actual implementation tries to be more efficient).
+                     */
+                    final Raster tile = source.getTile(srcMinTileX + 
(srcTileIndex % srcNumTileX),
+                                                       srcMinTileY + 
(srcTileIndex / srcNumTileX));
+                    final int numBands = Math.min(tile.getNumBands(), 
effectiveNumBands);
+                    final int scanline = tile.getWidth();
+                    final int xmin     = tile.getMinX();
+                    final int ymin     = tile.getMinY();
+                    final int xmax     = Math.addExact(xmin, scanline);
+                    final int ymax     = Math.addExact(ymin, tile.getHeight());
+                    double[]  xyBottom = coordinates[ymax & 1];
+                    for (int i=0, x=xmin; x <= xmax; x++) {     // Really the 
<= comparator.
+                        xyBottom[i++] = x;
+                        xyBottom[i++] = ymax;       // Bottom side of the last 
row of pixels.
+                    }
+                    fromSource.transform(xyBottom, 0, xyBottom, 0, scanline);
+                    double[] sampleValues = null;
+                    for (int y = ymax; --y >= ymin;) {
+                        final double[] xyTop = coordinates[y & 1];
+                        for (int i=0, x=xmin; x <= xmax; x++) {     // Really 
the <= comparator.
+                            xyTop[i++] = x;
+                            xyTop[i++] = y;
+                        }
+                        fromSource.transform(xyTop, 0, xyTop, 0, scanline);
+                        for (int i=0, x=xmin; x<xmax; x++) {        // Now the 
< comparator (exclusive bound).
+                            /*
+                             * At this point, we can have values in all bands 
of one pixel of the source image.
+                             * Find which pixels of that target image are 
overlapped by the source image pixel.
+                             * There are potentially many pixels.
+                             */
+                            for (int j = 0; j < sourcePixelCorners.length;) {
+                                final double v00 = xyTop   [i];
+                                final double v10 = xyTop   [i + BIDIMENSIONAL];
+                                final double v11 = xyBottom[i + BIDIMENSIONAL];
+                                final double v01 = xyBottom[i];
+                                final double off = imageOffset[i & 1];  // 
Even indexes are x, odd indexes are y.
+                                sourcePixelCorners[j++] = 
Math.min(Math.min(v00, v10), Math.min(v01, v11)) - off;
+                                sourcePixelCorners[j++] = 
Math.max(Math.max(v00, v10), Math.max(v01, v11)) - off;
+                                i++;    // After we have done x, move to y.
+                            }
+                            final int lowerX = Math.max(0,      (int) 
(Math.floor(sourcePixelCorners[0])));
+                            final int lowerY = Math.max(0,      (int) 
(Math.floor(sourcePixelCorners[2])));
+                            final int upperX = Math.min(width,  (int) 
(Math.ceil (sourcePixelCorners[1])));
+                            final int upperY = Math.min(height, (int) 
(Math.ceil (sourcePixelCorners[3])));
+                            if (lowerX < upperX && lowerY < upperY) {
+                                sampleValues = tile.getPixel(x, y, 
sampleValues);
+                                for (int py=lowerY; py<upperY; py++) {
+                                    final double weightY = 
Math.min(sourcePixelCorners[3], py + 1)
+                                                         - 
Math.max(sourcePixelCorners[2], py);
+                                    assert weightY > 0 && weightY <= 1: 
weightY;
+                                    final int chunkIndexBase = (py / 
CHUNK_SIZE) * chunksPerImageRow;
+                                    final int cellIndexBase  = (py % 
CHUNK_SIZE) * CHUNK_SIZE;
+                                    for (int px=lowerX; px<upperX; px++) {
+                                        final double weightX = 
Math.min(sourcePixelCorners[1], px + 1)
+                                                             - 
Math.max(sourcePixelCorners[0], px);
+                                        assert weightX > 0 && weightX <= 1: 
weightX;
+                                        final double weight = weightX * 
weightY;
+                                        final int cellIndex  = (px % 
CHUNK_SIZE) + cellIndexBase;
+                                        final int chunkIndex = (px / 
CHUNK_SIZE) + chunkIndexBase;
+                                        double[] tileData = data[chunkIndex];
+                                        if (tileData == null) {
+                                            data[chunkIndex] = tileData = new 
double[accumulatorValuesPerChunk()];
+                                        }
+                                        int valueIndex = cellIndex * 
chunkValueStride;
+                                        for (int j=0; j<numBands; j++) {
+                                            tileData[valueIndex++] += weight * 
sampleValues[j];
+                                            tileData[valueIndex++] += weight;
+                                        }
+                                    }
+                                }
+                            }
+                        }
+                        xyBottom = xyTop;
+                    }
+                } catch (TransformException e) {
+                    throw new BackingStoreException(e);
+                }
+                imageIndex++;
+            }
+            return data;
+        }
+    }
+}
diff --git 
a/endorsed/src/org.apache.sis.feature/main/org/apache/sis/image/BandAggregateImage.java
 
b/endorsed/src/org.apache.sis.feature/main/org/apache/sis/image/BandAggregateImage.java
index f0fae51ee6..347cc69ab2 100644
--- 
a/endorsed/src/org.apache.sis.feature/main/org/apache/sis/image/BandAggregateImage.java
+++ 
b/endorsed/src/org.apache.sis.feature/main/org/apache/sis/image/BandAggregateImage.java
@@ -106,8 +106,8 @@ class BandAggregateImage extends MultiSourceImage {
     final RenderedImage subset(final int[] bands, final ColorModel colors,
             final BandAggregateArgument<RenderedImage>.Unwrapper unwrapper)
     {
-        final RenderedImage[] sources = new RenderedImage[bands.length];
-        final int[][] bandsPerSource = new int[bands.length][];
+        final var sources = new RenderedImage[bands.length];
+        final var bandsPerSource = new int[bands.length][];
         int lower=0, upper=0, sourceIndex = -1;
         RenderedImage source = null;
         for (int i=0; i<bands.length; i++) {
diff --git 
a/endorsed/src/org.apache.sis.feature/main/org/apache/sis/image/ComputedImage.java
 
b/endorsed/src/org.apache.sis.feature/main/org/apache/sis/image/ComputedImage.java
index 1fadbc05ed..9431daf604 100644
--- 
a/endorsed/src/org.apache.sis.feature/main/org/apache/sis/image/ComputedImage.java
+++ 
b/endorsed/src/org.apache.sis.feature/main/org/apache/sis/image/ComputedImage.java
@@ -202,10 +202,9 @@ public abstract class ComputedImage extends PlanarImage 
implements Disposable {
      * and the {@linkplain SampleModel#getHeight() sample model height}
      * determines this {@linkplain #getTileHeight() image tile height}.
      *
-     * <h4>Design note</h4>
-     * {@code ComputedImage} requires the sample model to have exactly the 
desired tile size
-     * otherwise tiles created by {@link #createTile(int, int)} will consume 
more memory
-     * than needed.
+     * <p><b>Implementation note:</b>
+     * {@code ComputedImage} requires the sample model to have exactly the 
desired tile size,
+     * otherwise tiles created by {@link #createTile(int, int)} will consume 
more memory than needed.</p>
      *
      * @see #getSampleModel()
      */
@@ -412,13 +411,13 @@ public abstract class ComputedImage extends PlanarImage 
implements Disposable {
      * Returns the width of tiles in this image.
      * In {@code ComputedImage} implementation, this is fixed to {@link 
SampleModel#getWidth()}.
      *
-     * <h4>Design note</h4>
+     * <p><b>Design note:</b>
      * In theory it is legal to have a tile width smaller than the sample 
model width,
      * for example when a raster is a view over a subregion of another raster.
      * But this is not allowed in {@code ComputedImage} class, because it would
-     * cause {@link #createTile(int, int)} to consume more memory than 
necessary.
+     * cause {@link #createTile(int, int)} to consume more memory than 
necessary.</p>
      *
-     * @return the width of this image in pixels.
+     * @return the width (in pixels) of all tiles in this image.
      */
     @Override
     public final int getTileWidth() {
@@ -429,13 +428,13 @@ public abstract class ComputedImage extends PlanarImage 
implements Disposable {
      * Returns the height of tiles in this image.
      * In {@code ComputedImage} implementation, this is fixed to {@link 
SampleModel#getHeight()}.
      *
-     * <h4>Design note</h4>
+     * <p><b>Design note:</b>
      * In theory it is legal to have a tile height smaller than the sample 
model height,
      * for example when a raster is a view over a subregion of another raster.
      * But this is not allowed in {@code ComputedImage} class, because it would
-     * cause {@link #createTile(int, int)} to consume more memory than 
necessary.
+     * cause {@link #createTile(int, int)} to consume more memory than 
necessary.</p>
      *
-     * @return the height of this image in pixels.
+     * @return the height (in pixels) of all tiles in this image.
      */
     @Override
     public final int getTileHeight() {
diff --git 
a/endorsed/src/org.apache.sis.feature/main/org/apache/sis/image/ImageCombiner.java
 
b/endorsed/src/org.apache.sis.feature/main/org/apache/sis/image/ImageCombiner.java
index 222d96a232..8e69cb30a2 100644
--- 
a/endorsed/src/org.apache.sis.feature/main/org/apache/sis/image/ImageCombiner.java
+++ 
b/endorsed/src/org.apache.sis.feature/main/org/apache/sis/image/ImageCombiner.java
@@ -52,11 +52,11 @@ import org.apache.sis.measure.Units;
  * an image is <abbr>RGB</abbr> and the other image is <abbr>BVR</abbr>.
  * It is caller responsibility to ensure that bands are in the same order.</p>
  *
- * <h2>Alternative</h2>
+ * <p><b>Alternative:</b>
  * A single call to the {@link ImageProcessor#overlay 
ImageProcessor.overlay(…)} method can produce the same result
  * as multiple calls to the {@link #accept(RenderedImage)} method of this 
class. The main difference between the two
  * methods is that this class writes immediately in the given destination 
image, while {@code ImageProcessor} creates
- * an image which will compute the requested tiles on the fly.
+ * an image which will compute the requested tiles on the fly.</p>
  *
  * @author  Martin Desruisseaux (Geomatys)
  * @version 1.4
diff --git 
a/endorsed/src/org.apache.sis.feature/main/org/apache/sis/image/PixelIterator.java
 
b/endorsed/src/org.apache.sis.feature/main/org/apache/sis/image/PixelIterator.java
index 9692f5a4eb..4e7e6952c8 100644
--- 
a/endorsed/src/org.apache.sis.feature/main/org/apache/sis/image/PixelIterator.java
+++ 
b/endorsed/src/org.apache.sis.feature/main/org/apache/sis/image/PixelIterator.java
@@ -325,7 +325,7 @@ public class PixelIterator {
 
         /**
          * Sets the region (in pixel coordinates) where to perform the 
iteration.
-         * If this method is not invoked, then  by default iterators will 
traverse all pixels in the image or raster.
+         * If this method is not invoked, then by default iterators will 
traverse all pixels in the image or raster.
          * If a sub-area is specified, then the traversed area is the 
{@linkplain Rectangle#intersection(Rectangle)
          * intersection} of {@code subArea} with the image or {@linkplain 
Raster#getBounds() raster bounds}.
          *
@@ -790,7 +790,7 @@ public class PixelIterator {
                 x = currentLowerX;
             } else {
                 /*
-                 * SequenceType.LINEAR iteration order: before to move to next 
row, verify if there is
+                 * SequenceType.LINEAR iteration order: before to move to next 
row, verify if there are
                  * more tiles to traverse on the right side.
                  */
                 releaseTile();                          // Must be invoked 
before (tileX, tileY) change.
@@ -839,6 +839,14 @@ public class PixelIterator {
         return (py == y) && px >= currentLowerX && px < currentUpperX;
     }
 
+    /**
+     * Returns whether the iterator is at the beginning of a row other than 
the first row.
+     * This method can be used for detecting when the iterator changed the 
traversed row.
+     */
+    final boolean isBeginningOfNewRow() {
+        return x == lowerX && y != lowerY;
+    }
+
     /**
      * Returns the exception to throw when the tile at index ({@link #tileX}, 
{@link #tileY})
      * uses an incompatible sample model.
diff --git 
a/endorsed/src/org.apache.sis.feature/main/org/apache/sis/image/PlanarImage.java
 
b/endorsed/src/org.apache.sis.feature/main/org/apache/sis/image/PlanarImage.java
index cf549358dc..3a69b73381 100644
--- 
a/endorsed/src/org.apache.sis.feature/main/org/apache/sis/image/PlanarImage.java
+++ 
b/endorsed/src/org.apache.sis.feature/main/org/apache/sis/image/PlanarImage.java
@@ -111,6 +111,11 @@ import org.apache.sis.pending.jdk.JDK18;
  * @since SIS 1.1
  */
 public abstract class PlanarImage implements RenderedImage {
+    /**
+     * The {@value} value for identifying code expecting exactly 2 dimensions.
+     */
+    static final int BIDIMENSIONAL = 2;
+
     /**
      * Key for a property storing the name of the source of the data rendered 
by this image.
      * The name can be used as a label in a graphical user interface or for 
debugging purposes,
@@ -707,7 +712,7 @@ public abstract class PlanarImage implements RenderedImage {
      * The returned identifiers may also have subcategories. For example 
{@code "colorModel"} may be
      * subdivided with {@code "colorModel.numBands"} and {@code 
"colorModel.transferType"}.
      *
-     * <h4>Ignorable inconsistency</h4>
+     * <h4>Ignorable inconsistency in image properties</h4>
      * Inconsistency in {@code "width"} and {@code "height"} values may be 
acceptable
      * if all other verifications pass (in particular the {@code "numXTiles"} 
and {@code "numYTiles"} checks).
      * It happens when tiles in the last row or last column have some unused 
space compared to the image size.
diff --git 
a/endorsed/src/org.apache.sis.feature/main/org/apache/sis/image/PositionalConsistencyImage.java
 
b/endorsed/src/org.apache.sis.feature/main/org/apache/sis/image/PositionalConsistencyImage.java
index 465bc3dd62..a703f3f425 100644
--- 
a/endorsed/src/org.apache.sis.feature/main/org/apache/sis/image/PositionalConsistencyImage.java
+++ 
b/endorsed/src/org.apache.sis.feature/main/org/apache/sis/image/PositionalConsistencyImage.java
@@ -127,7 +127,7 @@ final class PositionalConsistencyImage extends 
SourceAlignedImage {
         final int tileMinY = tile.getMinY();
         final int tileMaxX = Math.addExact(tileMinX, scanline);
         final int tileMaxY = Math.addExact(tileMinY, tile.getHeight());
-        final double[] buffer = new double[scanline * 
Math.max(ResampledImage.BIDIMENSIONAL, toSource.getSourceDimensions())];
+        final double[] buffer = new double[scanline * Math.max(BIDIMENSIONAL, 
toSource.getSourceDimensions())];
         for (int y=tileMinY; y<tileMaxY; y++) {
             for (int i=0, x = tileMinX; x < tileMaxX; x++) {
                 buffer[i++] = x;
diff --git 
a/endorsed/src/org.apache.sis.feature/main/org/apache/sis/image/ResampledImage.java
 
b/endorsed/src/org.apache.sis.feature/main/org/apache/sis/image/ResampledImage.java
index 9cfcac1d90..675ddf9bc0 100644
--- 
a/endorsed/src/org.apache.sis.feature/main/org/apache/sis/image/ResampledImage.java
+++ 
b/endorsed/src/org.apache.sis.feature/main/org/apache/sis/image/ResampledImage.java
@@ -25,6 +25,7 @@ import java.awt.Dimension;
 import java.awt.Rectangle;
 import java.awt.geom.Area;
 import java.awt.geom.Rectangle2D;
+import java.awt.geom.AffineTransform;
 import java.awt.image.ColorModel;
 import java.awt.image.Raster;
 import java.awt.image.RenderedImage;
@@ -43,6 +44,7 @@ import 
org.apache.sis.referencing.operation.transform.TransformSeparator;
 import org.apache.sis.image.internal.shared.ImageUtilities;
 import org.apache.sis.image.internal.shared.FillValues;
 import org.apache.sis.feature.internal.Resources;
+import org.apache.sis.coverage.grid.PixelInCell;
 import org.apache.sis.util.ArraysExt;
 import org.apache.sis.util.Disposable;
 import org.apache.sis.util.ArgumentChecks;
@@ -60,17 +62,25 @@ import static 
org.apache.sis.image.internal.shared.ImageUtilities.LOGGER;
  * Resampling is the action of computing pixel values at possibly non-integral 
positions of a source image.
  * It can be used for projecting an image to another coordinate reference 
system,
  * for example from (<var>latitude</var>, <var>longitude</var>) to World 
Mercator.
- * The resampling is defined by a non-linear {@link MathTransform} (for 
example a map projection)
+ * The resampling is defined by a {@link MathTransform} (for example a map 
projection)
  * which converts pixel center coordinates from <em>this</em> image to pixel 
center coordinates
  * in the <em>source</em> image.
- * The converted coordinates usually contain fraction digits, in which case an 
interpolation is applied.
+ * The converted coordinates usually contain fraction digits, in which case an 
interpolation can be applied.
  *
- * <h2>Usage note</h2>
- * This class should be used with non-linear transforms such as map 
projections. It is technically
- * possible to use this class with linear transforms such as {@link 
java.awt.geom.AffineTransform},
- * but there is more efficient alternatives for linear cases (for example
- * {@linkplain java.awt.Graphics2D#drawRenderedImage(RenderedImage, 
java.awt.geom.AffineTransform)
- * specifying the affine transform at rendering time}).
+ * <p>This class is designed for use with non-linear transforms such as map 
projections.
+ * It is possible to use this class with linear transforms such as {@link 
AffineTransform},
+ * but there are more efficient alternatives for linear cases (for example,
+ * {@linkplain java.awt.Graphics2D#drawRenderedImage(RenderedImage, 
AffineTransform)
+ * specifying the affine transform at rendering time}).</p>
+ *
+ * <h2>Interpolated image <i>versus</i> aggregated image</h2>
+ * The algorithm used by this class (coordinates transformed from 
<em>this</em> to <em>source</em> image)
+ * is suitable to interpolations, which are themselves suitable to both 
upsampling (higher resolution) and
+ * downsampling (lower resolution).
+ * An algorithm using transforms in the opposite direction (from 
<em>source</em> image to <em>this</em> image)
+ * is also possible, but is more suitable to aggregation methods such as 
weighted average, median or mode,
+ * which are themselves better suited to downsampling rather than upsampling.
+ * That alternative approach is handled by the {@link AggregatedImage} class.
  *
  * @author  Martin Desruisseaux (Geomatys)
  * @author  Johann Sorel (Geomatys)
@@ -96,11 +106,6 @@ public class ResampledImage extends ComputedImage {
      */
     public static final String POSITIONAL_CONSISTENCY_KEY = 
"org.apache.sis.PositionalConsistency";
 
-    /**
-     * The {@value} value for identifying code expecting exactly 2 dimensions.
-     */
-    static final int BIDIMENSIONAL = 2;
-
     /**
      * Domain of pixel coordinates in this image.
      */
@@ -116,7 +121,7 @@ public class ResampledImage extends ComputedImage {
      * image. This transform should be an instance of {@link MathTransform2D}, 
but this is not required by this class
      * (a future version may allow interpolations in a 
<var>n</var>-dimensional cube).
      *
-     * @see org.apache.sis.coverage.grid.PixelInCell#CELL_CENTER
+     * @see PixelInCell#CELL_CENTER
      */
     protected final MathTransform toSource;
 
@@ -184,13 +189,14 @@ public class ResampledImage extends ComputedImage {
     private Shape validArea;
 
     /**
-     * Creates a new image which will resample the given image. The resampling 
operation is defined
-     * by a potentially non-linear transform from <em>this</em> image to the 
specified <em>source</em> image.
-     * That transform shall map {@linkplain 
org.apache.sis.coverage.grid.PixelInCell#CELL_CENTER pixel centers}.
+     * Creates a new image which will resample the given image. The resampling 
operation requires
+     * a potentially non-linear transform from <em>this</em> image to the 
specified <em>source</em> image.
+     * That transform shall map {@linkplain PixelInCell#CELL_CENTER pixel 
centers}.
      *
-     * <p>The {@code sampleModel} determines the tile size and the target data 
type. This is often the same sample
-     * model than the one used by the {@code source} image, but may also be 
different for forcing a different tile
-     * size or a different data type (e.g. {@code byte} versus {@code float}) 
for storing resampled values.
+     * <p>The given {@code sampleModel} determines the tile size and the 
target data type.
+     * This is often the same sample model as the one used by the {@code 
source} image,
+     * but may also be different for forcing a different tile size or a 
different data type
+     * (for example, casting {@code float} values to {@code byte}s) for 
storing resampled values.
      * If the specified sample model is not the same as the one used by the 
source image,
      * then subclass should override {@link #getColorModel()} for returning a 
color model which is
      * {@linkplain ColorModel#isCompatibleSampleModel(SampleModel) compatible 
with the sample model}.</p>
@@ -492,7 +498,7 @@ public class ResampledImage extends ComputedImage {
 
     /**
      * Gets a property from this image. Current default implementation 
supports the following keys
-     * (more properties may be added to this list in any future Apache SIS 
versions):
+     * (more properties may be added to this list in any future Apache 
<abbr>SIS</abbr> versions):
      *
      * <ul>
      *   <li>{@value #SOURCE_NAME_KEY}</li>
@@ -503,7 +509,6 @@ public class ResampledImage extends ComputedImage {
      *   <li>{@value #MASK_KEY} if the image uses floating point numbers.</li>
      * </ul>
      *
-     * <h4>Note on sample values</h4>
      * The sample resolutions are retained because they should have 
approximately the same values before and after
      * resampling. {@linkplain #STATISTICS_KEY Statistics} are not in this 
list because, while minimum and maximum
      * values should stay approximately the same, the average value and 
standard deviation may be quite different.
diff --git 
a/endorsed/src/org.apache.sis.feature/main/org/apache/sis/image/internal/shared/TiledImage.java
 
b/endorsed/src/org.apache.sis.feature/main/org/apache/sis/image/internal/shared/TiledImage.java
index 2493d31ddd..0077282734 100644
--- 
a/endorsed/src/org.apache.sis.feature/main/org/apache/sis/image/internal/shared/TiledImage.java
+++ 
b/endorsed/src/org.apache.sis.feature/main/org/apache/sis/image/internal/shared/TiledImage.java
@@ -17,6 +17,8 @@
 package org.apache.sis.image.internal.shared;
 
 import java.util.Map;
+import java.awt.Point;
+import java.awt.Rectangle;
 import java.awt.Image;
 import java.awt.image.Raster;
 import java.awt.image.ColorModel;
@@ -30,8 +32,10 @@ import org.apache.sis.util.ArgumentChecks;
  * This class may become public in a future version, but not yet because 
managing large tiled
  * images would require a more sophisticated class than current implementation.
  *
- * <p>This class should not perform any computation; all tiles are given at 
construction time.
- * This requirement makes this class thread-safe and concurrent without the 
need for synchronization.</p>
+ * <p>This class assumes that all tiles are provided at construction time with 
no deferred calculation.
+ * This assumption makes this class thread-safe and concurrent without the 
need for synchronization.
+ * If this assumption is not true, then subclasses should override the {@link 
#verify()} and
+ * {@link #getTile(int, int)} methods with synchronization.</p>
  *
  * @author  Rémi Maréchal (Geomatys)
  * @author  Martin Desruisseaux (Geomatys)
@@ -40,56 +44,78 @@ public class TiledImage extends PlanarImage {
     /**
      * The color model, or {@code null} if none.
      */
-    private final ColorModel colorModel;
+    protected final ColorModel colorModel;
 
     /**
-     * Number of pixels along X or Y axis in the whole rendered image.
+     * The sample model, either specified at construction time or inferred 
from the tiles.
+     * May be {@code null} if no sample model was found at construction time.
      */
-    private final int width, height;
+    protected final SampleModel sampleModel;
+
+    /**
+     * Number of pixels along <var>x</var> or <var>y</var> axis in the whole 
rendered image.
+     */
+    protected final int width, height;
+
+    /**
+     * Index of the first pixel in the image. Must be equals to the origin of 
the first tile.
+     * That first tile may be {@code null} if a subclass implements deferred 
computation.
+     */
+    protected final int minX, minY;
 
     /**
      * Index of the first tile in the image.
      */
-    private final int minTileX, minTileY;
+    protected final int minTileX, minTileY;
 
     /**
-     * The tiles. They must all use the same sample model.
+     * The tiles in row-major fashion. All tiles must all use the same sample 
model.
      */
-    private final Raster[] tiles;
+    protected final Raster[] tiles;
 
     /**
-     * Image properties, or an empty map if none.
+     * Image properties in an immutable map, or an empty map if none.
      */
-    private final Map<String, Object> properties;
+    protected final Map<String, Object> properties;
 
     /**
-     * Creates a new tiled image. The first tile in the given array must be the
-     * one located at the minimal tile indices. All tiles must have the same 
size
-     * and the same sample model and must be sorted in row-major fashion
+     * Creates a new tiled image.
+     * The first tile in the given array must be the one located at the 
minimal tile indices.
+     * The caller must ensure that origin of {@code bounds} is the origin of 
the first tile.
+     * All tiles must have the same size and the same sample model and must be 
sorted in row-major fashion
      * (this is not verified in current version, but may be in the future).
      *
      * @param properties  image properties, or {@code null} if none.
      * @param colorModel  the color model, or {@code null} if none.
-     * @param width       number of pixels along X axis in the whole rendered 
image.
-     * @param height      number of pixels along Y axis in the whole rendered 
image.
-     * @param minTileX    minimum tile index in the X direction.
-     * @param minTileY    minimum tile index in the Y direction.
+     * @param sampleModel the sample model used by all tiles.
+     * @param bounds      minimum (<var>x</var>, <var>y</var>) coordinates 
together with the image size.
+     * @param minTile     minimum tile indexes along <var>x</var> and 
<var>y</var> axes, or {@code null} for (0,0).
      * @param tiles       the tiles. Must contains at least one element. This 
array is not cloned.
      */
-    public TiledImage(final Map<String, ?> properties, final ColorModel 
colorModel,
-                      final int width, final int height, final int minTileX, 
final int minTileY,
-                      final Raster... tiles)
+    public TiledImage(final Map<String, ?> properties,
+                      final ColorModel     colorModel,
+                      final SampleModel    sampleModel,
+                      final Rectangle      bounds,
+                      final Point          minTile,
+                      final Raster...      tiles)
     {
-        ArgumentChecks.ensureStrictlyPositive("width",  width);
-        ArgumentChecks.ensureStrictlyPositive("height", height);
+        ArgumentChecks.ensureNonNull("sampleModel", sampleModel);
+        ArgumentChecks.ensureStrictlyPositive("width",  width  = bounds.width);
+        ArgumentChecks.ensureStrictlyPositive("height", height = 
bounds.height);
         ArgumentChecks.ensureNonEmpty        ("tiles",  tiles);
-        this.colorModel = colorModel;
-        this.width      = width;
-        this.height     = height;
-        this.minTileX   = minTileX;
-        this.minTileY   = minTileY;
-        this.tiles      = tiles;
-        this.properties = (properties != null) ? Map.copyOf(properties) : 
Map.of();
+        this.tiles       = tiles;
+        this.minX        = bounds.x;
+        this.minY        = bounds.y;
+        this.colorModel  = colorModel;
+        this.sampleModel = sampleModel;
+        this.properties  = (properties != null) ? Map.copyOf(properties) : 
Map.of();
+        if (minTile != null) {
+            minTileX = minTile.x;
+            minTileY = minTile.y;
+        } else {
+            minTileX = 0;
+            minTileY = 0;
+        }
     }
 
     /**
@@ -103,14 +129,12 @@ public class TiledImage extends PlanarImage {
      */
     @Override
     public String verify() {
-        final int minX       = getMinX();
-        final int minY       = getMinY();
         final int numXTiles  = getNumXTiles();
         final int tileWidth  = getTileWidth();
         final int tileHeight = getTileHeight();
-        final SampleModel sm = getSampleModel();
         for (int i=0; i < tiles.length; i++) {
             final Raster tile = tiles[i];
+            if (tile == null) continue;
             final int tx = i % numXTiles;
             final int ty = i / numXTiles;
             final int ox = minX + tx * tileWidth;
@@ -128,7 +152,7 @@ public class TiledImage extends PlanarImage {
                 if (tw != Math.min(tileWidth,  width  - ox)) return 
property(tx, ty, "width");
                 if (th != Math.min(tileHeight, height - oy)) return 
property(tx, ty, "height");
             }
-            if (!sm.equals(tile.getSampleModel())) return property(tx, ty, 
"sampleModel");
+            if (!sampleModel.equals(tile.getSampleModel())) return 
property(tx, ty, "sampleModel");
         }
         return super.verify();      // "width" and "height" properties should 
be checked last.
     }
@@ -153,7 +177,7 @@ public class TiledImage extends PlanarImage {
      */
     @Override
     public SampleModel getSampleModel() {
-        return tiles[0].getSampleModel();
+        return sampleModel;
     }
 
     /**
@@ -188,7 +212,7 @@ public class TiledImage extends PlanarImage {
      */
     @Override
     public int getMinX() {
-        return tiles[0].getMinX();
+        return minX;
     }
 
     /**
@@ -196,11 +220,11 @@ public class TiledImage extends PlanarImage {
      */
     @Override
     public int getMinY() {
-        return tiles[0].getMinY();
+        return minY;
     }
 
     /**
-     * Returns the number of pixels along X axis in the whole rendered image.
+     * Returns the number of pixels along <var>x</var> axis in the whole 
rendered image.
      */
     @Override
     public int getWidth() {
@@ -208,7 +232,7 @@ public class TiledImage extends PlanarImage {
     }
 
     /**
-     * Returns the number of pixels along Y axis in the whole rendered image.
+     * Returns the number of pixels along <var>y</var> axis in the whole 
rendered image.
      */
     @Override
     public int getHeight() {
@@ -220,7 +244,7 @@ public class TiledImage extends PlanarImage {
      */
     @Override
     public int getTileWidth() {
-        return tiles[0].getWidth();
+        return sampleModel.getWidth();
     }
 
     /**
@@ -228,11 +252,11 @@ public class TiledImage extends PlanarImage {
      */
     @Override
     public int getTileHeight() {
-        return tiles[0].getHeight();
+        return sampleModel.getHeight();
     }
 
     /**
-     * Returns the minimum tile index in the X direction.
+     * Returns the minimum tile index in the <var>x</var> direction.
      */
     @Override
     public final int getMinTileX() {
@@ -240,7 +264,7 @@ public class TiledImage extends PlanarImage {
     }
 
     /**
-     * Returns the minimum tile index in the Y direction.
+     * Returns the minimum tile index in the <var>y</var> direction.
      */
     @Override
     public final int getMinTileY() {
@@ -251,7 +275,7 @@ public class TiledImage extends PlanarImage {
      * Returns the tile at the given location in tile coordinates.
      */
     @Override
-    public Raster getTile(int tileX, int tileY) {
+    public Raster getTile(final int tileX, final int tileY) {
         final int numXTiles = getNumXTiles();
         final int numYTiles = getNumYTiles();
         checkTileIndex("tileX", minTileX, numXTiles, tileX);
diff --git 
a/endorsed/src/org.apache.sis.feature/main/org/apache/sis/image/internal/shared/WritableTiledImage.java
 
b/endorsed/src/org.apache.sis.feature/main/org/apache/sis/image/internal/shared/WritableTiledImage.java
index 27c3b8fa75..da3800ab6b 100644
--- 
a/endorsed/src/org.apache.sis.feature/main/org/apache/sis/image/internal/shared/WritableTiledImage.java
+++ 
b/endorsed/src/org.apache.sis.feature/main/org/apache/sis/image/internal/shared/WritableTiledImage.java
@@ -21,6 +21,7 @@ import java.util.LinkedHashMap;
 import java.awt.Point;
 import java.awt.Rectangle;
 import java.awt.image.ColorModel;
+import java.awt.image.SampleModel;
 import java.awt.image.Raster;
 import java.awt.image.TileObserver;
 import java.awt.image.WritableRaster;
@@ -30,6 +31,8 @@ import org.apache.sis.feature.internal.Resources;
 
 /**
  * A writable version of {@link TiledImage}.
+ * The array of tiles given to the constructor can contain null elements,
+ * in which case initially empty tiles will be created when first requested.
  *
  * @author  Martin Desruisseaux (Geomatys)
  */
@@ -56,25 +59,47 @@ public class WritableTiledImage extends TiledImage 
implements WritableRenderedIm
     /**
      * Creates a new tiled image.
      * The first tile in the given array must be the one located at the 
minimal tile indices.
+     * The caller must ensure that origin of {@code bounds} is the origin of 
the first tile.
      * All tiles must have the same size and the same sample model and must be 
sorted in row-major fashion.
      *
      * @param properties  image properties, or {@code null} if none.
      * @param colorModel  the color model, or {@code null} if none.
-     * @param width       number of pixels along X axis in the whole rendered 
image.
-     * @param height      number of pixels along Y axis in the whole rendered 
image.
-     * @param minTileX    minimum tile index in the X direction.
-     * @param minTileY    minimum tile index in the Y direction.
-     * @param tiles       the tiles. Must contains at least one element.
-     *                    This array is not cloned.
+     * @param sampleModel the sample model used by all tiles.
+     * @param bounds      minimum (<var>x</var>, <var>y</var>) coordinates 
together with the image size.
+     * @param minTile     minimum tile indexes along <var>x</var> and 
<var>y</var> axes, or {@code null} for (0,0).
+     * @param tiles       the tiles. Must contains at least one element. This 
array is not cloned.
      */
-    public WritableTiledImage(final Map<String, ?> properties, final 
ColorModel colorModel,
-                              final int width, final int height, final int 
minTileX, final int minTileY,
+    public WritableTiledImage(final Map<String, ?> properties,
+                              final ColorModel     colorModel,
+                              final SampleModel    sampleModel,
+                              final Rectangle      bounds,
+                              final Point          minTile,
                               final WritableRaster... tiles)
     {
-        super(properties, colorModel, width, height, minTileX, minTileY, 
tiles);
+        super(properties, colorModel, sampleModel, bounds, minTile, tiles);
         writables = new LinkedHashMap<>();
     }
 
+    /**
+     * Verifies whether image layout information and tile coordinates are 
consistent.
+     *
+     * @hidden
+     */
+    @Override
+    public String verify() {
+        synchronized (tiles) {
+            return super.verify();
+        }
+    }
+
+    /**
+     * Returns the sample model specified or inferred at construction time.
+     */
+    @Override
+    public SampleModel getSampleModel() {
+        return sampleModel;
+    }
+
     /**
      * Adds an observer to be notified when a tile is checked out for writing.
      * If the observer is already present, it will receive multiple 
notifications.
@@ -98,6 +123,29 @@ public class WritableTiledImage extends TiledImage 
implements WritableRenderedIm
         observers = WritableUntiledImage.removeTileObserver(observers, 
observer);
     }
 
+    /**
+     * Returns the tile at the given location in tile coordinates.
+     * If the tile is null, an initially empty tile is created.
+     */
+    @Override
+    public final Raster getTile(final int tileX, final int tileY) {
+        final int numXTiles = getNumXTiles();
+        final int numYTiles = getNumYTiles();
+        checkTileIndex("tileX", minTileX, numXTiles, tileX);
+        checkTileIndex("tileY", minTileY, numYTiles, tileY);
+        final int index = (tileX - minTileX) + (tileY - minTileY) * numXTiles;
+        synchronized (tiles) {
+            Raster tile = tiles[index];
+            if (tile == null) {
+                final int x = ImageUtilities.tileToPixelX(this, tileX);
+                final int y = ImageUtilities.tileToPixelY(this, tileY);
+                tile = WritableRaster.createWritableRaster(sampleModel, new 
Point(x, y));
+                tiles[index] = tile;
+            }
+            return tile;
+        }
+    }
+
     /**
      * Checks out a tile for writing. If the same tile is checked out many 
times
      * before to be released, only the first checkout is notified to listeners.
@@ -108,8 +156,8 @@ public class WritableTiledImage extends TiledImage 
implements WritableRenderedIm
      */
     @Override
     public WritableRaster getWritableTile(final int tileX, final int tileY) {
-        final WritableRaster tile = (WritableRaster) super.getTile(tileX, 
tileY);
-        final Point key = new Point(tileX, tileY);
+        final var tile = (WritableRaster) getTile(tileX, tileY);
+        final var key = new Point(tileX, tileY);
         final Integer count;
         synchronized (writables) {
             count = writables.merge(key, 1, (old, one) -> old + 1);
@@ -130,7 +178,7 @@ public class WritableTiledImage extends TiledImage 
implements WritableRenderedIm
      */
     @Override
     public void releaseWritableTile(final int tileX, final int tileY) {
-        final Point key = new Point(tileX, tileY);
+        final var key = new Point(tileX, tileY);
         final Integer count;
         final boolean close;
         synchronized (writables) {
diff --git 
a/endorsed/src/org.apache.sis.feature/main/org/apache/sis/image/package-info.java
 
b/endorsed/src/org.apache.sis.feature/main/org/apache/sis/image/package-info.java
index 4be38ce913..2ccdd5a27e 100644
--- 
a/endorsed/src/org.apache.sis.feature/main/org/apache/sis/image/package-info.java
+++ 
b/endorsed/src/org.apache.sis.feature/main/org/apache/sis/image/package-info.java
@@ -17,7 +17,7 @@
 
 /**
  * Provides helper classes for handling Java2D rendered images together with 
some operations.
- * This package does not provide any geospatial functionalities;
+ * This package does not provide any geospatial functionalities,
  * it works only on sample or pixel values stored in {@link 
java.awt.image.RenderedImage}s.
  * Those rendered images have the following capabilities:
  *
@@ -27,12 +27,10 @@
  *   <li>Images can be tiled.</li>
  * </ul>
  *
- * This package is used as a basis for
- * {@linkplain org.apache.sis.metadata.iso.spatial.DefaultGeorectified 
georectified} or
- * {@linkplain org.apache.sis.metadata.iso.spatial.DefaultGeoreferenceable 
georeferenceable}
- * <i>grid coverages</i>.
+ * This package is used as a basis for georeferenced
+ * {@linkplain org.apache.sis.coverage.grid.GridCoverage grid coverages}.
  *
- * <h2>Usage note</h2>
+ * <h2>Usage pattern for writing in images</h2>
  * Some images are writable. But modifying pixel values should be done by 
invoking the {@code getWritableTile(…)}
  * and {@code releaseWritableTile(…)} methods of {@link 
java.awt.image.WritableRenderedImage} interface.
  * Do not cast directly a {@link java.awt.image.Raster} to {@link 
java.awt.image.WritableRaster}
@@ -42,7 +40,8 @@
  * @author  Rémi Maréchal (Geomatys)
  * @author  Martin Desruisseaux (Geomatys)
  * @author  Johann Sorel (Geomatys)
- * @version 1.7
+ * @version 1.8
+ *
  * @since SIS 1.0
  */
 package org.apache.sis.image;
diff --git 
a/endorsed/src/org.apache.sis.feature/test/org/apache/sis/coverage/grid/ResampledGridCoverageTest.java
 
b/endorsed/src/org.apache.sis.feature/test/org/apache/sis/coverage/grid/ResampledGridCoverageTest.java
index 26f63f50eb..04433d9329 100644
--- 
a/endorsed/src/org.apache.sis.feature/test/org/apache/sis/coverage/grid/ResampledGridCoverageTest.java
+++ 
b/endorsed/src/org.apache.sis.feature/test/org/apache/sis/coverage/grid/ResampledGridCoverageTest.java
@@ -21,6 +21,7 @@ import java.util.Random;
 import java.util.EnumSet;
 import java.util.stream.IntStream;
 import java.awt.Color;
+import java.awt.Point;
 import java.awt.Rectangle;
 import java.awt.image.BufferedImage;
 import java.awt.image.DataBuffer;
@@ -164,7 +165,7 @@ public final class ResampledGridCoverageTest extends 
TestCase {
      */
     private GridCoverage createCoverageND(final boolean withTime) {
         random = TestUtilities.createRandomNumberGenerator();
-        final BufferedImage image = new BufferedImage(2*QS, 2*QS, 
BufferedImage.TYPE_3BYTE_BGR);
+        final var image = new BufferedImage(2*QS, 2*QS, 
BufferedImage.TYPE_3BYTE_BGR);
         final int[] color = new int[QS*QS];
         /* Upper-left  quarter */ // Keep default value, which is black.
         /* Upper-right quarter */ Arrays.fill(color, Color.RED  .getRGB()); 
image.setRGB(QS,  0, QS, QS, color, 0, QS);
@@ -178,12 +179,14 @@ public final class ResampledGridCoverageTest extends 
TestCase {
         final int minX = random.nextInt(5) - 2;
         final int minY = random.nextInt(5) - 2;
         GridGeometry gg = createGridGeometryND(withTime ? 
HardCodedCRS.WGS84_4D : HardCodedCRS.WGS84_3D, 0, 1, 2, 3, false);
-        final TiledImage shiftedImage = new TiledImage(null,
+        final var shiftedImage = new TiledImage(
+                null,
                 image.getColorModel(),
-                image.getWidth(), image.getHeight(),        // Image size
-                random.nextInt(32) - 10,                    // minTileX
-                random.nextInt(32) - 10,                    // minTileY
+                image.getSampleModel(),
+                new Rectangle(minX, minY, image.getWidth(), image.getHeight()),
+                new Point(random.nextInt(32) - 10, random.nextInt(32) - 10),   
 // Minimum tile index.
                 image.getRaster().createTranslatedChild(minX, minY));
+        assertNull(shiftedImage.verify());
         return new GridCoverage2D(gg, null, shiftedImage);
     }
 
diff --git 
a/endorsed/src/org.apache.sis.feature/test/org/apache/sis/image/InterpolationTest.java
 
b/endorsed/src/org.apache.sis.feature/test/org/apache/sis/image/InterpolationTest.java
index 8d4c545d28..375e57b2b5 100644
--- 
a/endorsed/src/org.apache.sis.feature/test/org/apache/sis/image/InterpolationTest.java
+++ 
b/endorsed/src/org.apache.sis.feature/test/org/apache/sis/image/InterpolationTest.java
@@ -19,6 +19,7 @@ package org.apache.sis.image;
 import java.nio.DoubleBuffer;
 import java.awt.Point;
 import java.awt.Dimension;
+import java.awt.Rectangle;
 import java.awt.image.DataBuffer;
 import java.awt.image.WritableRaster;
 import java.awt.image.BandedSampleModel;
@@ -83,17 +84,16 @@ public final class InterpolationTest extends TestCase {
      *         1 for nearest, 2 for bilinear, 4 for bicubic.
      */
     private void createImage(final int support) {
-        final WritableRaster raster = WritableRaster.createWritableRaster(
-                new BandedSampleModel(DataBuffer.TYPE_FLOAT, XUP-XMIN, 
YUP-YMIN, 1),
-                new Point(XMIN, YMIN));
-
+        final var sm = new BandedSampleModel(DataBuffer.TYPE_FLOAT, XUP-XMIN, 
YUP-YMIN, 1);
+        final WritableRaster raster = WritableRaster.createWritableRaster(sm, 
new Point(XMIN, YMIN));
         float value = 0;
         for (int y=YMIN; y<YUP; y++) {
             for (int x=XMIN; x<XUP; x++) {
                 raster.setSample(x, y, 0, value++);
             }
         }
-        final TiledImage source = new TiledImage(null, null, XUP-XMIN, 
YUP-YMIN, 0, 0, raster);
+        final var bounds = new Rectangle(XMIN, YMIN, XUP - XMIN, YUP - YMIN);
+        final var source = new TiledImage(null, null, sm, bounds, null, 
raster);
         assertNull(source.verify());
         iterator = new PixelIterator.Builder().setWindowSize(new 
Dimension(support, support)).create(source);
         window   = iterator.createWindow(TransferType.DOUBLE);
diff --git 
a/endorsed/src/org.apache.sis.feature/test/org/apache/sis/image/MaskedImageTest.java
 
b/endorsed/src/org.apache.sis.feature/test/org/apache/sis/image/MaskedImageTest.java
index 7caa72e7d3..4764545ac8 100644
--- 
a/endorsed/src/org.apache.sis.feature/test/org/apache/sis/image/MaskedImageTest.java
+++ 
b/endorsed/src/org.apache.sis.feature/test/org/apache/sis/image/MaskedImageTest.java
@@ -290,7 +290,7 @@ public final class MaskedImageTest extends TestCase {
      */
     private static BufferedImage monoTile(final int[] pixels) {
         assertEquals(WIDTH*HEIGHT, pixels.length, "Input raster must be " + 
WIDTH + "×" + HEIGHT);
-        final BufferedImage image = new BufferedImage(WIDTH, HEIGHT, 
BufferedImage.TYPE_BYTE_INDEXED, colorPalette());
+        final var image = new BufferedImage(WIDTH, HEIGHT, 
BufferedImage.TYPE_BYTE_INDEXED, colorPalette());
         final WritableRaster raster = image.getRaster();
         raster.setPixels(0, 0, WIDTH, HEIGHT, pixels);
         return image;
@@ -301,8 +301,14 @@ public final class MaskedImageTest extends TestCase {
      * Image size is {@value #WIDTH}×{@value #HEIGHT} pixels.
      */
     private static RenderedImage multiTile() {
-        final TiledImage image = new TiledImage(null, colorPalette(), WIDTH, 
HEIGHT, 0, 0,
-                tile(         0,           0, 0),
+        final WritableRaster firstTile = tile(0, 0, 0);
+        final var image = new TiledImage(
+                null,
+                colorPalette(),
+                firstTile.getSampleModel(),
+                new Rectangle(WIDTH, HEIGHT),
+                null,
+                firstTile,
                 tile(TILE_WIDTH,           0, 1),
                 tile(         0, TILE_HEIGHT, 3),
                 tile(TILE_WIDTH, TILE_HEIGHT, 2));
@@ -353,7 +359,7 @@ public final class MaskedImageTest extends TestCase {
         if (source == null) {
             source = monoTile();
         }
-        final BufferedImage debugImg = new BufferedImage(source.getWidth(), 
source.getHeight(), BufferedImage.TYPE_INT_RGB);
+        final var debugImg = new BufferedImage(source.getWidth(), 
source.getHeight(), BufferedImage.TYPE_INT_RGB);
         final Graphics2D painter = debugImg.createGraphics();
         painter.drawRenderedImage(source, new AffineTransform());
         if (geometry != null) {
diff --git 
a/endorsed/src/org.apache.sis.feature/test/org/apache/sis/image/TiledImageMock.java
 
b/endorsed/src/org.apache.sis.feature/test/org/apache/sis/image/TiledImageMock.java
index 6f0d208d61..ab6e4dc07e 100644
--- 
a/endorsed/src/org.apache.sis.feature/test/org/apache/sis/image/TiledImageMock.java
+++ 
b/endorsed/src/org.apache.sis.feature/test/org/apache/sis/image/TiledImageMock.java
@@ -591,6 +591,9 @@ public final class TiledImageMock extends PlanarImage 
implements WritableRendere
      */
     @SuppressWarnings("exports")
     public synchronized WritableTiledImage toWritableTiledImage() {
-        return new WritableTiledImage(null, null, width, height, minTileX, 
minTileY, tiles);
+        final var minTile = new Point(minTileX, minTileY);
+        final var image = new WritableTiledImage(null, colorModel, 
sampleModel, getBounds(), minTile, tiles);
+        assertNull(image.verify());
+        return image;
     }
 }
diff --git 
a/endorsed/src/org.apache.sis.referencing/main/org/apache/sis/referencing/operation/transform/MathTransforms.java
 
b/endorsed/src/org.apache.sis.referencing/main/org/apache/sis/referencing/operation/transform/MathTransforms.java
index a3ce6f34e0..7c08560c9e 100644
--- 
a/endorsed/src/org.apache.sis.referencing/main/org/apache/sis/referencing/operation/transform/MathTransforms.java
+++ 
b/endorsed/src/org.apache.sis.referencing/main/org/apache/sis/referencing/operation/transform/MathTransforms.java
@@ -68,6 +68,14 @@ import org.opengis.coordinate.MismatchedDimensionException;
  * @since SIS 0.5
  */
 public final class MathTransforms {
+    /**
+     * The {@value} value for identifying code expecting exactly 2 dimensions.
+     * We provide this constant for clarity only, its value will never change.
+     *
+     * @see AbstractMathTransform2D#DIMENSION
+     */
+    static final int BIDIMENSIONAL = 2;
+
     /**
      * Do not allow instantiation of this class.
      */
@@ -111,7 +119,7 @@ public final class MathTransforms {
      */
     public static LinearTransform swapTwoFirstAxes(final int dimension) {
         ArgumentChecks.ensurePositive("dimension", dimension);
-        if (dimension < 2) {
+        if (dimension < BIDIMENSIONAL) {
             return IdentityTransform.create(dimension);
         }
         final int[] indices = ArraysExt.range(0, dimension);
@@ -235,13 +243,13 @@ public final class MathTransforms {
                                 DoubleDouble.of(m.getNumber(0, 0), true),
                                 DoubleDouble.of(m.getNumber(0, 1), true));
                     }
-                    case 2: {
+                    case BIDIMENSIONAL: {
                         if (!Matrices.hasNaN(matrix)) {
                             return AffineTransform2D.create(matrix);
                         }
                     }
                 }
-            } else if (sourceDimension == 2) {
+            } else if (sourceDimension == BIDIMENSIONAL) {
                 return new ProjectiveTransform2D(matrix);
             }
         }
@@ -367,7 +375,7 @@ public final class MathTransforms {
         final SpecializableTransform tr;
         if (specializations.isEmpty()) {
             return global;
-        } else if (global.getSourceDimensions() == 2 && 
global.getTargetDimensions() == 2) {
+        } else if (global.getSourceDimensions() == BIDIMENSIONAL && 
global.getTargetDimensions() == BIDIMENSIONAL) {
             tr = new SpecializableTransform2D(global, specializations);
         } else {
             tr = new SpecializableTransform(global, specializations);
@@ -630,7 +638,7 @@ public final class MathTransforms {
         if (transform == null || transform instanceof MathTransform2D) {
             return (MathTransform2D) transform;
         } else {
-            ArgumentChecks.ensureDimensionsMatch("transform", 2, 2, transform);
+            ArgumentChecks.ensureDimensionsMatch("transform", BIDIMENSIONAL, 
BIDIMENSIONAL, transform);
             return new TransformAdapter2D(transform);
         }
     }
diff --git 
a/endorsed/src/org.apache.sis.storage/main/org/apache/sis/storage/tiling/TiledGridCoverage.java
 
b/endorsed/src/org.apache.sis.storage/main/org/apache/sis/storage/tiling/TiledGridCoverage.java
index 282c58009d..3e4e2ea538 100644
--- 
a/endorsed/src/org.apache.sis.storage/main/org/apache/sis/storage/tiling/TiledGridCoverage.java
+++ 
b/endorsed/src/org.apache.sis.storage/main/org/apache/sis/storage/tiling/TiledGridCoverage.java
@@ -585,7 +585,7 @@ public abstract class TiledGridCoverage extends 
GridCoverage {
         if (name != null) {
             name = name.toFullyQualifiedName();
         }
-        final RenderedImage image;
+        final PlanarImage image;
         try {
             final int[] tileLower = new int[dimension];         // Indices of 
first tile to read, inclusive.
             final int[] tileUpper = new int[dimension];         // Indices of 
last tile to read, exclusive.
@@ -640,9 +640,11 @@ public abstract class TiledGridCoverage extends 
GridCoverage {
                  * in the area of interest now. I/O operations, if needed, 
happen in `readTiles(…)` call.
                  */
                 final Raster[] result = readTiles(iterator);
-                image = new TiledImage(properties, colors,
-                        imageSize[xDimension], imageSize[yDimension],
-                        tileLower[xDimension], tileLower[yDimension], result);
+                final var minTile = new Point    (tileLower[xDimension], 
tileLower[yDimension]);
+                final var bounds  = new Rectangle(imageSize[xDimension], 
imageSize[yDimension]);
+                bounds.x = offsetAOI[xDimension];
+                bounds.y = offsetAOI[yDimension];
+                image = new TiledImage(properties, colors, model, bounds, 
minTile, result);
             }
         } catch (DisjointExtentException | CannotEvaluateException e) {
             throw e;
@@ -650,6 +652,11 @@ public abstract class TiledGridCoverage extends 
GridCoverage {
             throw new 
CannotEvaluateException(Resources.forLocale(listeners.getLocale())
                         .getString(Resources.Keys.CanNotRenderImage_1, name), 
e);
         }
+        /*
+         * Debugging tip: invoke `image.verify()` here if the image seems 
wrong.
+         * We don't do that systematically because inconsistency reported in 
the
+         * "width" or "height" properties are sometime normal.
+         */
         return image;
     }
 

Reply via email to