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

commit 0b7a73c206fea301fe208372c081cb48d616b0c3
Author: Martin Desruisseaux <[email protected]>
AuthorDate: Mon Nov 23 16:47:31 2026 +0100

    Fix problems with creation of ColorModel and SampleModel:
    - Reduce confusion about whether the maximum is inclusive or exclusive.
    - Get the original color model after converting back to integer values.
    - Do not convert too early to floating point values in GUI.
    - Store values in single precision when sufficient.
---
 .../sis/coverage/grid/ConvertedGridCoverage.java   |  62 ++++++++++--
 .../sis/coverage/grid/GridCoverageBuilder.java     |   2 +-
 .../apache/sis/coverage/grid/ImageRenderer.java    |   2 +-
 .../apache/sis/image/BandedSampleConverter.java    |  14 ++-
 .../main/org/apache/sis/image/Interpolation.java   |   4 +-
 .../main/org/apache/sis/image/Visualization.java   |   4 +-
 .../image/internal/shared/ColorModelFactory.java   |  38 ++++----
 .../image/internal/shared/ColorScaleBuilder.java   | 104 +++++----------------
 .../sis/image/internal/shared/ImageUtilities.java  |  67 +++++++++++++
 .../sis/image/internal/shared/RasterFactory.java   |   4 +-
 .../image/internal/shared/ScaledColorModel.java    |  15 +--
 .../image/internal/shared/ScaledColorSpace.java    |  22 +++--
 .../internal/shared/ColorModelBuilderTest.java     |  31 +++---
 .../internal/shared/ScaledColorSpaceTest.java      |   9 +-
 .../org/apache/sis/map/coverage/RenderingData.java |   9 +-
 .../sis/storage/geotiff/ImageFileDirectory.java    |  18 ++--
 .../org/apache/sis/gui/coverage/Stretching.java    |   2 +-
 17 files changed, 235 insertions(+), 172 deletions(-)

diff --git 
a/endorsed/src/org.apache.sis.feature/main/org/apache/sis/coverage/grid/ConvertedGridCoverage.java
 
b/endorsed/src/org.apache.sis.feature/main/org/apache/sis/coverage/grid/ConvertedGridCoverage.java
index 10bd1b84b5..d3bc6a6200 100644
--- 
a/endorsed/src/org.apache.sis.feature/main/org/apache/sis/coverage/grid/ConvertedGridCoverage.java
+++ 
b/endorsed/src/org.apache.sis.feature/main/org/apache/sis/coverage/grid/ConvertedGridCoverage.java
@@ -19,7 +19,6 @@ package org.apache.sis.coverage.grid;
 import java.util.List;
 import java.util.Arrays;
 import java.util.ArrayList;
-import java.util.Optional;
 import java.util.Collection;
 import java.util.stream.Stream;
 import java.awt.image.RenderedImage;
@@ -28,11 +27,14 @@ import org.opengis.referencing.operation.MathTransform1D;
 import org.opengis.referencing.operation.TransformException;
 import org.opengis.referencing.operation.NoninvertibleTransformException;
 import org.apache.sis.referencing.operation.transform.MathTransforms;
+import org.apache.sis.coverage.Category;
 import org.apache.sis.coverage.SampleDimension;
 import org.apache.sis.measure.MeasurementRange;
 import org.apache.sis.measure.NumberRange;
+import org.apache.sis.math.NumberType;
 import org.apache.sis.image.DataType;
 import org.apache.sis.image.ImageProcessor;
+import org.apache.sis.util.logging.Logging;
 
 // Specific to the geoapi-3.1 and geoapi-4.0 branches:
 import org.opengis.coverage.CannotEvaluateException;
@@ -152,9 +154,9 @@ final class ConvertedGridCoverage extends 
DerivedGridCoverage {
             targets.add(tgt);
             if (src != tgt) {
                 MathTransform1D tr = 
src.getTransferFunction().orElse(identity);
-                Optional<MathTransform1D> complete = tgt.getTransferFunction();
-                if (complete.isPresent()) {
-                    tr = MathTransforms.concatenate(tr, 
complete.get().inverse());
+                MathTransform1D complete = 
tgt.getTransferFunction().orElse(null);
+                if (complete != null) {
+                    tr = MathTransforms.concatenate(tr, complete.inverse());
                 }
                 converters[i] = tr;
             }
@@ -172,7 +174,7 @@ final class ConvertedGridCoverage extends 
DerivedGridCoverage {
      *
      * @param  targets    the sample dimensions for which to get the data type.
      * @param  converted  whether the image will hold converted or packed 
values.
-     * @param  source     if the type cannot be determined, coverage from 
which to inherit the type as a fallback.
+     * @param  source     the coverage from which the converted values are 
computed.
      * @return the data type (never null).
      *
      * @see GridCoverage#getBandType()
@@ -181,9 +183,8 @@ final class ConvertedGridCoverage extends 
DerivedGridCoverage {
         NumberRange<?> union = null;
         boolean allowsNaN = false;
         for (final SampleDimension dimension : targets) {
-            final Optional<NumberRange<?>> c = dimension.getSampleRange();
-            if (c.isPresent()) {
-                final NumberRange<?> range = c.get();
+            final NumberRange<?> range = 
dimension.getSampleRange().orElse(null);
+            if (range != null) {
                 if (union == null) {
                     union = range;
                 } else {
@@ -198,7 +199,9 @@ final class ConvertedGridCoverage extends 
DerivedGridCoverage {
                     union = union.unionAny(range);
                 }
             }
-            if (!allowsNaN) allowsNaN = dimension.allowsNaN();
+            if (!allowsNaN) {
+                allowsNaN = dimension.allowsNaN();
+            }
         }
         if (union == null) {
             return source.getBandType();
@@ -207,9 +210,50 @@ final class ConvertedGridCoverage extends 
DerivedGridCoverage {
         if (allowsNaN) {
             type = type.toFloat();
         }
+        /*
+         * If double-precision floating point values have been selected 
(probably because at least
+         * one of the given ranges was using that data type), check if this is 
really necessary.
+         */
+reduce: if (type == DataType.DOUBLE) {
+            for (SampleDimension dimension : targets) {
+                dimension = dimension.forConvertedValues(!converted);
+                for (final Category category : dimension.getCategories()) {
+                    final NumberRange<?> range = category.getSampleRange();
+                    if (!NumberType.isInteger(range.getElementType())) {
+                        break reduce;
+                    }
+                    final MathTransform1D tr = 
category.getTransferFunction().orElse(null);
+                    if (tr != null) {   // Ignore qualitative categories.
+                        if (requireDoublePrecision(tr, range.getMinDouble()) ||
+                            requireDoublePrecision(tr, range.getMaxDouble()))
+                        {
+                            break reduce;
+                        }
+                    }
+                }
+            }
+            type = DataType.FLOAT;
+        }
         return type;
     }
 
+    /**
+     * Tests whether double precision is required for differentiating the 
given sample value
+     * with the neighbor sample value.
+     *
+     * @param  tr     the transform used for converting sample values.
+     * @param  value  the sample value to test.
+     * @return whether double-precision is required.
+     */
+    private static boolean requireDoublePrecision(final MathTransform1D tr, 
final double value) {
+        try {
+            return Math.abs(tr.derivative(value)) < Math.ulp((float) 
tr.transform(value));
+        } catch (TransformException e) {
+            Logging.ignorableException(GridExtent.LOGGER, GridCoverage.class, 
"forConvertedValues", e);
+            return true;
+        }
+    }
+
     /**
      * Returns the constant identifying the primitive type used for storing 
sample values.
      */
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 b4d64cbe22..4c9c6a192c 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
@@ -587,7 +587,7 @@ public class GridCoverageBuilder {
     {
         final ColorModel colors;
         final var colorizer = new 
ColorScaleBuilder(ColorScaleBuilder.GRAYSCALE, null, false);
-        if (colorizer.initialize(sm, bands.get(visibleBand)) || 
colorizer.initialize(sm, visibleBand)) {
+        if (colorizer.initialize(sm, bands.get(visibleBand)) || 
colorizer.initialize(null, sm, visibleBand)) {
             colors = colorizer.createColorModel(sm, bands.size(), visibleBand);
         } else {
             colors = ColorScaleBuilder.NULL_COLOR_MODEL;
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 d0a02a46d6..36c9b87e77 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
@@ -772,7 +772,7 @@ public class ImageRenderer {
         final var colorizer = new ColorScaleBuilder(colors, null, false);
         final ColorModel cm;
         final SampleModel sm = raster.getSampleModel();
-        if (colorizer.initialize(sm, bands[visibleBand]) || 
colorizer.initialize(sm, visibleBand)) {
+        if (colorizer.initialize(sm, bands[visibleBand]) || 
colorizer.initialize(null, sm, visibleBand)) {
             DataType type = DataType.forDataBufferType(buffer.getDataType());
             cm = colorizer.createColorModel(type, bands.length, visibleBand);
         } else {
diff --git 
a/endorsed/src/org.apache.sis.feature/main/org/apache/sis/image/BandedSampleConverter.java
 
b/endorsed/src/org.apache.sis.feature/main/org/apache/sis/image/BandedSampleConverter.java
index c67bdd55d4..786d12235c 100644
--- 
a/endorsed/src/org.apache.sis.feature/main/org/apache/sis/image/BandedSampleConverter.java
+++ 
b/endorsed/src/org.apache.sis.feature/main/org/apache/sis/image/BandedSampleConverter.java
@@ -197,7 +197,7 @@ class BandedSampleConverter extends WritableComputedImage {
             this.sourceRanges = sourceRanges;
             this.converters   = converters;
             final int numBands = converters.length;
-            final int visibleBand;
+            int visibleBand;
             /*
              * Create the sample model and get the color model if it was 
explicitly specified.
              */
@@ -218,14 +218,18 @@ class BandedSampleConverter extends WritableComputedImage 
{
              */
             if (colorModel == null && (colorModel = 
searchColorModelInSources(source)) == null) {
                 SampleDimension sd = null;
-                if (sampleDimensions != null && visibleBand >= 0 && 
visibleBand < sampleDimensions.size()) {
+                if (visibleBand < 0) {
+                    visibleBand = 0;    // Arbitrary choice.
+                }
+                if (sampleDimensions != null && visibleBand < 
sampleDimensions.size()) {
                     sd = sampleDimensions.get(visibleBand);
                 }
+                final SampleModel sourceSM = source.getSampleModel();
                 final var builder = new 
ColorScaleBuilder(ColorScaleBuilder.GRAYSCALE, null, false);
-                if (builder.initialize(source.getSampleModel(), sd) ||
-                    builder.initialize(source.getColorModel()))
+                if (builder.initialize(sourceSM, sd) ||
+                    builder.initialize(source.getColorModel(), sourceSM, 
visibleBand))
                 {
-                    colorModel = builder.createColorModel(targetType, 
numBands, Math.max(visibleBand, 0));
+                    colorModel = builder.createColorModel(targetType, 
numBands, visibleBand);
                 }
             }
         }
diff --git 
a/endorsed/src/org.apache.sis.feature/main/org/apache/sis/image/Interpolation.java
 
b/endorsed/src/org.apache.sis.feature/main/org/apache/sis/image/Interpolation.java
index cbceff357e..2b2b50dcf6 100644
--- 
a/endorsed/src/org.apache.sis.feature/main/org/apache/sis/image/Interpolation.java
+++ 
b/endorsed/src/org.apache.sis.feature/main/org/apache/sis/image/Interpolation.java
@@ -115,13 +115,13 @@ public abstract class Interpolation {
      * If the given image uses an index color model, interpolating the indexed 
values does not produce the
      * expected colors. Safest approach is to disable completely 
interpolations in that case.
      *
-     * <h4>Design note</h4>
+     * <p><b>Design note</b>
      * We could interpolate if we knew that all index values, without 
exception (i.e. no index for missing values),
      * are related to measurements by a linear function. In practice it rarely 
happens, because there is usually
      * at least one index value reserved for missing values. Scientific data 
in SIS are usually stored as floating
      * point type (with missing values mapped to NaN), which cannot be 
associated with {@link IndexColorModel}.
      * For now we do not try to perform a more sophisticated detection of 
which interpolations are allowed,
-     * but a future SIS version may revisit this policy if needed.
+     * but a future <abbr>SIS</abbr> version may revisit this policy if 
needed.</p>
      *
      * @return {@link #NEAREST} if interpolations should be restricted to 
nearest-neighbor, or {@code this} otherwise.
      */
diff --git 
a/endorsed/src/org.apache.sis.feature/main/org/apache/sis/image/Visualization.java
 
b/endorsed/src/org.apache.sis.feature/main/org/apache/sis/image/Visualization.java
index 7227566885..204174db4a 100644
--- 
a/endorsed/src/org.apache.sis.feature/main/org/apache/sis/image/Visualization.java
+++ 
b/endorsed/src/org.apache.sis.feature/main/org/apache/sis/image/Visualization.java
@@ -319,7 +319,7 @@ final class Visualization extends ResampledImage {
                      * There is no call to `rescaleMainRange(…)` because the 
following code already uses the range
                      * specified by the ColorModel, if available.
                      */
-                    initialized = builder.initialize(sourceCM);
+                    initialized = builder.initialize(sourceCM, sourceSM, 
visibleBand);
                     if (!initialized) {
                         if (coloredSource instanceof RecoloredImage) {
                             final var colored = (RecoloredImage) coloredSource;
@@ -329,7 +329,7 @@ final class Visualization extends ResampledImage {
                             }
                         }
                         if (!initialized) {
-                            initialized = builder.initialize(sourceSM, 
visibleBand);
+                            initialized = builder.initialize(colorModel, 
sourceSM, visibleBand);
                         }
                     }
                 }
diff --git 
a/endorsed/src/org.apache.sis.feature/main/org/apache/sis/image/internal/shared/ColorModelFactory.java
 
b/endorsed/src/org.apache.sis.feature/main/org/apache/sis/image/internal/shared/ColorModelFactory.java
index f5fd6df411..6b89c2fb9d 100644
--- 
a/endorsed/src/org.apache.sis.feature/main/org/apache/sis/image/internal/shared/ColorModelFactory.java
+++ 
b/endorsed/src/org.apache.sis.feature/main/org/apache/sis/image/internal/shared/ColorModelFactory.java
@@ -131,7 +131,7 @@ public final class ColorModelFactory {
     private final int visibleBand;
 
     /**
-     * The minimum (inclusive) and maximum (exclusive) sample values.
+     * The minimum (inclusive) and maximum (<em>inclusive</em>) sample values.
      * If no category or color map was specified, then the minimum and maximum 
are set to the standard range of values.
      * For integer types, this is the full range of values allowed by that 
type. For floating-point types, this is 0…1.
      *
@@ -182,11 +182,11 @@ public final class ColorModelFactory {
         for (final ColorsForRange entry : colors) {
             final NumberRange<?> range = entry.sampleRange;
             final double min = range.getMinDouble(true);
-            final double max = range.getMaxDouble(false);
+            final double max = range.getMaxDouble(true);
             if (min < minimum) minimum = min;
             if (max > maximum) maximum = max;
-            final int lower = Math.round((float) min);
-            final int upper = Math.round((float) max);
+            final int lower = Numerics.clamp(Math.round(min));
+            final int upper = 
Numerics.clamp(Math.round(range.getMaxDouble(false)));
             if (lower < upper) {
                 if (lower < 0 || upper > 0x10000) {
                     starts = ArraysExt.EMPTY_INT;
@@ -224,15 +224,15 @@ public final class ColorModelFactory {
          * If no category or color map was specified, default to the standard 
range of values.
          * For floating point types, the standard range of values is defined 
by Java2D as 0 … 1.
          */
-        if (minimum >= maximum) {
+        if (!(minimum <= maximum)) {
             minimum = 0;
-            maximum = 1;
+            maximum = 1;    // Inclusive.
             if (ImageUtilities.isIntegerType(dataType)) {
                 if (dataType == DataBuffer.TYPE_SHORT) {
                     minimum = Short.MIN_VALUE;
-                    maximum = Short.MAX_VALUE + 1;  // Exclusive.
+                    maximum = Short.MAX_VALUE;
                 } else {
-                    maximum = 1L << DataBuffer.getDataTypeSize(dataType);
+                    maximum = 
Numerics.bitmask(DataBuffer.getDataTypeSize(dataType)) - 1;
                 }
             }
         }
@@ -506,20 +506,20 @@ public final class ColorModelFactory {
      * @param  dataType     the color model type.
      * @param  numBands     the number of bands for the color model (usually 
1).
      * @param  visibleBand  the band to be made visible (usually 0). All other 
bands (if any) will be ignored.
-     * @param  lower        the minimum value, inclusive.
-     * @param  upper        the maximum value, exclusive.
+     * @param  minimum      the minimum value, inclusive.
+     * @param  maximum      the maximum value, inclusive.
      * @param  colors       the colors to use for the range of sample values.
      * @return a color model suitable for {@link RenderedImage} objects with 
values in the given ranges.
      */
     public static ColorModel createColorScale(final int dataType, final int 
numBands, final int visibleBand,
-                                              final double lower, final double 
upper, final Color... colors)
+                                              final double minimum, final 
double maximum, final Color... colors)
     {
         ArgumentChecks.ensureNonEmpty("colors", colors);
         if (colors.length == 2 && colors[0].getRGB() == 0xFF000000 && 
colors[1].getRGB() == 0xFFFFFFFF) {
-            return createGrayScale(dataType, numBands, visibleBand, lower, 
upper);
+            return createGrayScale(dataType, numBands, visibleBand, minimum, 
maximum);
         }
         return createPiecewise(dataType, numBands, visibleBand, new 
ColorsForRange[] {
-            new ColorsForRange(null, new NumberRange<>(Double.class, lower, 
true, upper, false), colors, true, null)
+            new ColorsForRange(null, new NumberRange<>(Double.class, minimum, 
true, maximum, true), colors, true, null)
         });
     }
 
@@ -534,8 +534,8 @@ public final class ColorModelFactory {
      * @param  dataType       the color model type as one of {@code 
DataBuffer.TYPE_*} constants.
      * @param  numComponents  the number of components.
      * @param  visibleBand    the band to use for computing colors.
-     * @param  minimum        the minimal sample value expected.
-     * @param  maximum        the maximal sample value expected.
+     * @param  minimum        the minimal sample value expected (inclusive).
+     * @param  maximum        the maximal sample value expected (inclusive).
      * @return the color model for the given range of values.
      *
      * @see RasterFactory#createGrayScaleImage(int, int, int, int, int, 
double, double)
@@ -618,7 +618,7 @@ public final class ColorModelFactory {
         double minimum, maximum;
         if (range != null) {
             minimum = range.getMinDouble();
-            maximum = range.getMaxDouble();
+            maximum = range.getMaxDouble();     // Taken as inclusive.
         } else {
             minimum = 0;
             maximum = 1;
@@ -896,8 +896,10 @@ public final class ColorModelFactory {
     @Override
     public String toString() {
         final var buffer = new StringBuilder(Strings.toString(getClass(),
-                "dataType", DataType.forDataBufferType(dataType), "numBands", 
numBands, "visibleBand", visibleBand,
-                "range", NumberRange.create(minimum, true, maximum, false)));
+                "dataType",    DataType.forDataBufferType(dataType),
+                "numBands",    numBands,
+                "visibleBand", visibleBand,
+                "range",       NumberRange.create(minimum, true, maximum, 
true)));
         final int n = (pieceStarts != null) ? pieceStarts.length : 0;
         for (int i=0; i<n; i++) {
             final String start = Integer.toString(pieceStarts[i]);
diff --git 
a/endorsed/src/org.apache.sis.feature/main/org/apache/sis/image/internal/shared/ColorScaleBuilder.java
 
b/endorsed/src/org.apache.sis.feature/main/org/apache/sis/image/internal/shared/ColorScaleBuilder.java
index 1881e11caf..62ee095fe5 100644
--- 
a/endorsed/src/org.apache.sis.feature/main/org/apache/sis/image/internal/shared/ColorScaleBuilder.java
+++ 
b/endorsed/src/org.apache.sis.feature/main/org/apache/sis/image/internal/shared/ColorScaleBuilder.java
@@ -39,7 +39,6 @@ import org.apache.sis.image.DataType;
 import org.apache.sis.measure.NumberRange;
 import org.apache.sis.util.ArgumentChecks;
 import org.apache.sis.util.ArraysExt;
-import org.apache.sis.util.internal.shared.Numerics;
 import org.apache.sis.util.resources.Errors;
 import org.apache.sis.util.resources.Vocabulary;
 
@@ -293,72 +292,29 @@ public final class ColorScaleBuilder {
     }
 
     /**
-     * Applies colors on the range of values of a raster using given sample 
model. The 0 index will be reserved
-     * for NaN value, and indices in the [1 … 255] range will be mapped to the 
range of sample values that can
-     * be stored in the specified band.
+     * Applies colors on the range of values of a raster using the given color 
model and/or sample model.
+     * The colors in the given color model are ignored because they will be 
replaced by colors specified
+     * by this {@code ColorScaleBuilder}. Only the range of values will be 
fetched, if such range exists.
+     * {@link ScaledColorModel} range has precedence and {@link SampleModel} 
range is used as as fallback.
+     * In compact mode, the 0 index will be reserved for NaN value and indices 
in the [1 … 255] will be
+     * mapped to the given range.
      *
-     * @param  source  sample model of raster to be colored, or {@code null}.
-     * @param  band    raster band to be colored.
+     * @param  source       the color model from which to get a range of 
values, or {@code null}.
+     * @param  sourceSM     sample model associated to the given color model, 
or {@code null} if unknown.
+     * @param  visibleBand  the band which will be shown, or -1 if unknown.
      * @return {@code true} on success, or {@code false} if no range of values 
has been found.
      * @throws IllegalStateException if a sample dimension is already defined 
on this colorizer.
      */
-    public boolean initialize(final SampleModel source, final int band) {
+    public boolean initialize(final ColorModel source, final SampleModel 
sourceSM, final int visibleBand) {
         checkInitializationStatus(false);
-        if (DataType.isInteger(source)) {
-            long minimum = 0;
-            long maximum = Numerics.bitmask(source.getSampleSize(band)) - 1;
-            if (!DataType.isUnsigned(source)) {
-                maximum >>>= 1;
-                minimum = ~maximum;
-            }
-            initialize(minimum, maximum);
+        defaultRange = ImageUtilities.inferRangeFromType(source, sourceSM, 
visibleBand);
+        if (defaultRange != null) {
+            applyDefaultRange();
             return true;
         }
         return false;
     }
 
-    /**
-     * Uses the given color model for mapping range of values to new colors. 
The colors in the given color model
-     * are ignored (because they will be replaced by colors specified by this 
{@code ColorScaleBuilder});
-     * only the range of values will be fetched, if such range exists.
-     *
-     * @param  source  the color model from which to get a range of values, or 
{@code null}.
-     * @return {@code true} on success, or {@code false} if no range of values 
has been found.
-     * @throws IllegalStateException if a sample dimension is already defined 
on this colorizer.
-     */
-    public boolean initialize(final ColorModel source) {
-        checkInitializationStatus(false);
-        if (source != null) {
-            final ColorSpace cs = source.getColorSpace();
-            if (cs instanceof ScaledColorSpace) {
-                final ScaledColorSpace scs = (ScaledColorSpace) cs;
-                initialize(scs.offset, scs.maximum, source.getTransferType());
-                return true;
-            }
-            /*
-             * If the color model uses integer type, compute the maximal value 
based on the number of bits.
-             * The main use case is `IndexColorModel` with values on 16 bits 
but with a color ramp that does
-             * not exploit the full range allowed by 16 bits.
-             */
-            if (ImageUtilities.isIntegerType(source.getTransferType())) {
-                long maximum = Numerics.bitmask(source.getPixelSize()) - 1;
-                long minimum = 0;
-                if (source instanceof IndexColorModel) {
-                    final IndexColorModel indexed = (IndexColorModel) source;
-                    int t = indexed.getMapSize();
-                    if (t <= maximum) maximum = t - 1L;     // Inclusive.
-                    t = indexed.getTransparentPixel();
-                    if (t == 0) minimum = 1;
-                }
-                if (minimum < maximum) {
-                    initialize(minimum, maximum);
-                    return true;
-                }
-            }
-        }
-        return false;
-    }
-
     /*
      * Do not provide methods taking Raster or RenderedImage argument.
      * See class javadoc for rational.
@@ -390,21 +346,6 @@ public final class ColorScaleBuilder {
         applyDefaultRange();
     }
 
-    /**
-     * Applies colors on the given range of values.
-     * This method does the same work as {@link #initialize(double, double, 
int)},
-     * but is preferred to the latter when the sample values are known to be 
integer values.
-     *
-     * @param  minimum  minimum value, inclusive.
-     * @param  maximum  maximum value, inclusive.
-     * @throws IllegalStateException if a sample dimension is already defined 
on this colorizer.
-     */
-    public void initialize(final long minimum, final long maximum) {
-        checkInitializationStatus(false);
-        defaultRange = NumberRange.create(minimum, true, maximum, true);
-        applyDefaultRange();
-    }
-
     /**
      * Initializes this builder with the {@link #defaultRange} value.
      */
@@ -467,7 +408,7 @@ public final class ColorScaleBuilder {
                         widest = entry;
                     }
                 }
-                defaultRange = NumberRange.create(minimum, true, maximum, 
false);
+                defaultRange = NumberRange.create(minimum, true, maximum, 
true);
                 if (widest != null && widestSpan != 
widest.sampleRange.getSpan()) {
                     widest.sampleRange = defaultRange;
                     target = null;      // For recomputing the transfer 
function later.
@@ -561,8 +502,8 @@ reuse:  if (source != null) {
                 if (lower >= MAX_VALUE) {
                     throw new 
IllegalArgumentException(Resources.format(Resources.Keys.TooManyQualitatives));
                 }
-                final NumberRange<Integer> targetRange = 
NumberRange.create(lower, true, ++lower, false);
-                if (mapper.put(targetRange, entry) == null) {
+                final NumberRange<Integer> targetRange = 
NumberRange.create(lower, true, lower++, true);
+                if (mapper.putIfAbsent(targetRange, entry) == null) {
                     final double value = sourceRange.getMinDouble();
                     /*
                      * In the usual case where we have a mix of quantitative 
and qualitative categories,
@@ -606,7 +547,7 @@ reuse:  if (source != null) {
          */
         if (deferred == 0 && themes != null) {
             if (defaultRange == null) {
-                defaultRange = NumberRange.create(0, true, Short.MAX_VALUE + 
1, false);
+                defaultRange = NumberRange.create(0, true, Short.MAX_VALUE, 
true);
             }
             // Following loop will usually be executed only once.
             for (final NumberRange<?> sourceRange : 
defaultRange.subtractAny(themes)) {
@@ -623,18 +564,18 @@ reuse:  if (source != null) {
          * all remaining values in the [0 … 255] range, but code below is 
tolerant to arbitrary number of ranges.
          */
         final int base = lower;
-        final double toIndexRange = (MAX_VALUE + 1 - base) / span;
+        final double toIndexRange = (MAX_VALUE - base) / span;
         span = 0;
         for (int i=0; i<deferred; i++) {
             final ColorsForRange entry = entries[i];
             span += entry.sampleRange.getSpan();
-            final int upper = Math.toIntExact(Math.round(span * toIndexRange) 
+ base);
+            final int upper = Math.toIntExact(Math.round(span * toIndexRange) 
+ base + 1);  // Exclusive.
             if (upper <= lower) {
                 // May happen if too many qualitative categories have been 
added by previous loop.
                 throw new 
IllegalArgumentException(Resources.format(Resources.Keys.TooManyQualitatives));
             }
             final NumberRange<Integer> samples = NumberRange.create(lower, 
true, upper, false);
-            if (mapper.put(samples, entry) == null) {
+            if (mapper.putIfAbsent(samples, entry) == null) {
                 builder.addQuantitative(entry.name(), samples, 
entry.sampleRange);
             }
             lower = upper;
@@ -651,8 +592,9 @@ reuse:  if (source != null) {
         target = builder.build();
         for (final Category category : target.getCategories()) {
             final NumberRange<?> packed = category.getSampleRange();
-            mapper.get(packed).sampleRange = packed;
-            // A NullPointerException on above line would be a bug in our 
construction of `mapper`.
+            @SuppressWarnings("element-type-mismatch")
+            ColorsForRange entry = mapper.get(packed);
+            entry.sampleRange = packed;     // NullPointerException would be a 
bug in our construction of `mapper`.
         }
     }
 
diff --git 
a/endorsed/src/org.apache.sis.feature/main/org/apache/sis/image/internal/shared/ImageUtilities.java
 
b/endorsed/src/org.apache.sis.feature/main/org/apache/sis/image/internal/shared/ImageUtilities.java
index e3a8af4f53..bdad223571 100644
--- 
a/endorsed/src/org.apache.sis.feature/main/org/apache/sis/image/internal/shared/ImageUtilities.java
+++ 
b/endorsed/src/org.apache.sis.feature/main/org/apache/sis/image/internal/shared/ImageUtilities.java
@@ -39,6 +39,7 @@ import org.apache.sis.image.DataType;
 import org.apache.sis.image.PlanarImage;
 import org.apache.sis.system.Modules;
 import org.apache.sis.math.NumberType;
+import org.apache.sis.measure.NumberRange;
 import org.apache.sis.util.internal.shared.Numerics;
 import org.apache.sis.util.resources.Vocabulary;
 import static 
org.apache.sis.util.internal.shared.Numerics.COMPARISON_THRESHOLD;
@@ -393,6 +394,72 @@ public final class ImageUtilities {
         return true;
     }
 
+    /**
+     * Infers the maximal range of values expected for an image having the 
specified color and sample model.
+     * If the raster data type {@linkplain #isIntegerType(int) is an integer}, 
then the returned range will be
+     * parameterized with type {@code Long} or smaller. Otherwise, it is 
parameterized with type {@code Double}
+     * or {@code Float}.
+     *
+     * @param  cm           the color model from which to infer the range of 
values, or {@code null}.
+     * @param  sm           sample model associated to the given color model, 
or {@code null} if unknown.
+     * @param  visibleBand  the sample model band for which to infer the range 
of values, or -1 if unknown.
+     * @return the range of values, or {@code null} if no range of values 
could be inferred.
+     */
+    public static NumberRange<?> inferRangeFromType(final ColorModel cm, final 
SampleModel sm, final int visibleBand) {
+        final int dataType;
+        if (sm != null) {
+            dataType = sm.getDataType();
+        } else if (cm != null) {
+            dataType = cm.getTransferType();
+        } else {
+            return null;
+        }
+        if (cm != null) {
+            final ColorSpace cs = cm.getColorSpace();
+            if (cs instanceof ScaledColorSpace) {
+                final var scs = (ScaledColorSpace) cs;
+                if (visibleBand < 0 || scs.visibleBand == visibleBand) {
+                    final double minimum = scs.offset;
+                    final double maximum = scs.maximum;
+                    if (isIntegerType(dataType)) {
+                        return NumberRange.create(Math.round(minimum), true, 
Math.round(maximum), true);
+                    } else {
+                        return NumberRange.create(minimum, true, maximum, 
true);
+                    }
+                }
+            }
+        }
+        /*
+         * If the color model uses integer type, compute the maximal value 
based on the number of bits.
+         * The main use case is `IndexColorModel` with values on 16 bits but 
with a color ramp that does
+         * not exploit the full range allowed by 16 bits.
+         */
+        if (isIntegerType(dataType)) {
+            final int numBits;
+            if (sm != null && visibleBand >= 0) {
+                numBits = sm.getSampleSize(visibleBand);
+            } else {
+                numBits = cm.getPixelSize();
+            }
+            long minimum = 0;
+            long maximum = Numerics.bitmask(numBits) - 1;
+            if (cm instanceof IndexColorModel) {
+                final var indexed = (IndexColorModel) cm;
+                int t = indexed.getMapSize();
+                if (t <= maximum) maximum = t - 1;      // Inclusive.
+                t = indexed.getTransparentPixel();
+                if (t == 0) minimum = 1;
+            } else if (!DataType.isUnsigned(sm)) {
+                maximum >>>= 1;
+                minimum = ~maximum;
+            }
+            if (minimum < maximum) {
+                return NumberRange.create(minimum, true, maximum, true);
+            }
+        }
+        return null;
+    }
+
     /**
      * Converts a <var>x</var> pixel coordinates to a tile index.
      *
diff --git 
a/endorsed/src/org.apache.sis.feature/main/org/apache/sis/image/internal/shared/RasterFactory.java
 
b/endorsed/src/org.apache.sis.feature/main/org/apache/sis/image/internal/shared/RasterFactory.java
index adf3e41cf2..94751f23cf 100644
--- 
a/endorsed/src/org.apache.sis.feature/main/org/apache/sis/image/internal/shared/RasterFactory.java
+++ 
b/endorsed/src/org.apache.sis.feature/main/org/apache/sis/image/internal/shared/RasterFactory.java
@@ -81,8 +81,8 @@ public final class RasterFactory {
      * @param  height         the desired image height.
      * @param  numComponents  the number of components.
      * @param  visibleBand    the band to use for computing colors.
-     * @param  minimum        the minimal sample value expected.
-     * @param  maximum        the maximal sample value expected.
+     * @param  minimum        the minimal sample value expected (inclusive).
+     * @param  maximum        the maximal sample value expected (inclusive).
      * @return the color space for the given range of values.
      */
     public static BufferedImage createGrayScaleImage(final int dataType, final 
int width, final int height,
diff --git 
a/endorsed/src/org.apache.sis.feature/main/org/apache/sis/image/internal/shared/ScaledColorModel.java
 
b/endorsed/src/org.apache.sis.feature/main/org/apache/sis/image/internal/shared/ScaledColorModel.java
index a2a96223e2..4b5a14a097 100644
--- 
a/endorsed/src/org.apache.sis.feature/main/org/apache/sis/image/internal/shared/ScaledColorModel.java
+++ 
b/endorsed/src/org.apache.sis.feature/main/org/apache/sis/image/internal/shared/ScaledColorModel.java
@@ -32,18 +32,13 @@ import org.apache.sis.feature.internal.Resources;
  *
  * @author  Martin Desruisseaux (Geomatys)
  */
+@SuppressWarnings("EqualsAndHashcode")
 final class ScaledColorModel extends ComponentColorModel {
     /**
      * The mask to apply for getting a single color component.
      * This is also the maximum (inclusive) color/alpha value.
      */
-    private static final int MASK = 0xFF;
-
-    /**
-     * Size of the range of color values. Since minimum value is zero,
-     * this range is also the maximum (exclusive) color/alpha value.
-     */
-    static final int RANGE = 0x100;
+    private static final int MASK = ScaledColorSpace.MAXIMUM;
 
     /**
      * The object from which to get the coefficients for converting values to 
colors.
@@ -146,15 +141,15 @@ final class ScaledColorModel extends ComponentColorModel {
      * Returns {@code true} if the given object is also an instance of {@link 
ScaledColorModel}
      * with equals color space and same transfer type.
      *
-     * <h4>Implementation note</h4>
+     * <p><b>Implementation note</b>
      * We have to override this method because the {@link 
ComponentColorModel#equals(Object)} implementation
      * is confused by our overriding of {@link #getTransparency()} method. 
However, we do not need to override
-     * {@link #hashCode()}.
+     * {@link #hashCode()}.</p>
      */
     @Override
     public boolean equals(final Object obj) {
         if (obj instanceof ScaledColorModel) {
-            final ScaledColorModel other = (ScaledColorModel) obj;
+            final var other = (ScaledColorModel) obj;
             return transferType == other.getTransferType() && 
cs.equals(other.cs);
         }
         return false;
diff --git 
a/endorsed/src/org.apache.sis.feature/main/org/apache/sis/image/internal/shared/ScaledColorSpace.java
 
b/endorsed/src/org.apache.sis.feature/main/org/apache/sis/image/internal/shared/ScaledColorSpace.java
index 51050dca2f..da97edda77 100644
--- 
a/endorsed/src/org.apache.sis.feature/main/org/apache/sis/image/internal/shared/ScaledColorSpace.java
+++ 
b/endorsed/src/org.apache.sis.feature/main/org/apache/sis/image/internal/shared/ScaledColorSpace.java
@@ -40,9 +40,15 @@ final class ScaledColorSpace extends ColorSpace {
     private static final long serialVersionUID = -5146474397268513490L;
 
     /**
-     * The scaling factor from sample values to RGB values. The target RGB 
values will be in range 0
-     * to 255 inclusive. Note that the target range is different than the 
range of {@link ColorSpace}
-     * normalized values; methods in this class has to divide values by 
{@value ScaledColorModel#RANGE}.
+     * The maximum value, inclusive. Must be a power of 2 minus 1.
+     */
+    static final int MAXIMUM = 0xFF;
+
+    /**
+     * The scaling factor from sample values to <abbr>RGB</abbr> values.
+     * The target <abbr>RGB</abbr> values will be in range 0 to 255 inclusive.
+     * Note that the target range is different than the range of {@link 
ColorSpace} normalized values.
+     * Therefore, methods in this class have to divide values by {@value 
#MAXIMUM}.
      */
     final double scale;
 
@@ -52,7 +58,7 @@ final class ScaledColorSpace extends ColorSpace {
     final double offset;
 
     /**
-     * The maximum value specified at construction time.
+     * The maximum value (inclusive) specified at construction time.
      */
     final double maximum;
 
@@ -74,7 +80,7 @@ final class ScaledColorSpace extends ColorSpace {
         super(TYPE_GRAY, numComponents);
         this.visibleBand = visibleBand;
         this.maximum     = maximum;
-        this.scale       = ScaledColorModel.RANGE / (maximum - minimum);
+        this.scale       = MAXIMUM / (maximum - minimum);
         this.offset      = minimum;
     }
 
@@ -100,7 +106,7 @@ final class ScaledColorSpace extends ColorSpace {
      */
     @Override
     public float[] toRGB(final float[] samples) {
-        float value = Math.min(1, (float) ((samples[visibleBand] - offset) * 
(1d/ScaledColorModel.RANGE * scale)));
+        float value = Math.min(1, (float) ((samples[visibleBand] - offset) * 
scale / MAXIMUM));
         if (!(value >= 0)) value = 0;                   // Use `!` for 
replacing NaN.
         return new float[] {value, value, value};
     }
@@ -115,7 +121,7 @@ final class ScaledColorSpace extends ColorSpace {
     public float[] fromRGB(final float[] color) {
         final float[] values = new float[getNumComponents()];
         values[visibleBand] = (float) ((color[0] + color[1] + color[2])
-                            / (3d/ScaledColorModel.RANGE * scale) + offset);
+                            / (3d/MAXIMUM * scale) + offset);
         return values;
     }
 
@@ -143,7 +149,7 @@ final class ScaledColorSpace extends ColorSpace {
     public float[] fromCIEXYZ(final float[] color) {
         final float[] values = new float[getNumComponents()];
         values[visibleBand] = (float) ((color[0] / 0.9642f + color[1] + 
color[2] / 0.8249f)
-                            / (3d/ScaledColorModel.RANGE * scale) + offset);
+                            / (3d/MAXIMUM * scale) + offset);
         return values;
     }
 
diff --git 
a/endorsed/src/org.apache.sis.feature/test/org/apache/sis/image/internal/shared/ColorModelBuilderTest.java
 
b/endorsed/src/org.apache.sis.feature/test/org/apache/sis/image/internal/shared/ColorModelBuilderTest.java
index d4a2e26e04..0faf79d85d 100644
--- 
a/endorsed/src/org.apache.sis.feature/test/org/apache/sis/image/internal/shared/ColorModelBuilderTest.java
+++ 
b/endorsed/src/org.apache.sis.feature/test/org/apache/sis/image/internal/shared/ColorModelBuilderTest.java
@@ -95,7 +95,7 @@ public final class ColorModelBuilderTest extends TestCase {
      */
     @Test
     public void testSampleDimension() throws TransformException {
-        final SampleDimension sd = new SampleDimension.Builder()
+        final var sd = new SampleDimension.Builder()
                 .addQualitative ("No data", Float.NaN)
                 .addQuantitative("Low temperature", -5, 24, Units.CELSIUS)
                 .addQuantitative("Hot temperature", 25, 40, Units.CELSIUS)
@@ -105,7 +105,7 @@ public final class ColorModelBuilderTest extends TestCase {
         final var colorizer = new 
ColorScaleBuilder(ColorScaleBuilder.GRAYSCALE, null, true);
         assertTrue(colorizer.initialize(null, sd));
         final var dt = 
DataType.forDataBufferType(ColorScaleBuilder.TYPE_COMPACT);
-        final var cm = (IndexColorModel) colorizer.createColorModel(dt, 1, 0); 
     // Must be first.
+        final var cm = assertInstanceOf(IndexColorModel.class, 
colorizer.createColorModel(dt, 1, 0));      // Must be first.
         /*
          * Test conversion of a few sample values to packed values.
          */
@@ -126,27 +126,28 @@ public final class ColorModelBuilderTest extends TestCase 
{
               0, 0x00000000,
               1, 0x00000000,
               2, 0xFF000000,
-             16, 0xFF161616,
+             16, 0xFF151515,
              32, 0xFF2E2E2E,
-             48, 0xFF474747,
+             48, 0xFF464646,
              64, 0xFF5F5F5F,
-             80, 0xFF787878,
+             80, 0xFF777777,
              96, 0xFF909090,
-            112, 0xFFA9A9A9,
-            128, 0xFFC2C2C2,
-            144, 0xFFDADADA,
-            160, 0xFFF3F3F3,
-            176, 0xFF151515,
-            192, 0xFF444444,
-            208, 0xFF747474,
-            224, 0xFFA3A3A3,
-            240, 0xFFD3D3D3,
+            112, 0xFFA8A8A8,
+            128, 0xFFC0C0C0,
+            144, 0xFFD9D9D9,
+            160, 0xFFF1F1F1,
+            176, 0xFF121212,
+            192, 0xFF424242,
+            208, 0xFF727272,
+            224, 0xFFA2A2A2,
+            240, 0xFFD2D2D2,
             255, 0xFFFFFFFF
         };
         for (int k=0; k<expected.length;) {
             final int i = expected[k++];
             final int e = expected[k++];
-            assertEquals(e, cm.getRGB(i));
+            final int a = cm.getRGB(i);
+            assertEquals(e, a, () -> "RGB[" + i + "]: " + 
Integer.toHexString(e) + " ≠ " + Integer.toHexString(a));
         }
     }
 }
diff --git 
a/endorsed/src/org.apache.sis.feature/test/org/apache/sis/image/internal/shared/ScaledColorSpaceTest.java
 
b/endorsed/src/org.apache.sis.feature/test/org/apache/sis/image/internal/shared/ScaledColorSpaceTest.java
index 3d16685e1c..8264d5c31d 100644
--- 
a/endorsed/src/org.apache.sis.feature/test/org/apache/sis/image/internal/shared/ScaledColorSpaceTest.java
+++ 
b/endorsed/src/org.apache.sis.feature/test/org/apache/sis/image/internal/shared/ScaledColorSpaceTest.java
@@ -19,7 +19,6 @@ package org.apache.sis.image.internal.shared;
 import java.util.Random;
 import java.awt.Transparency;
 import java.awt.image.BufferedImage;
-import java.awt.image.ColorModel;
 import java.awt.image.ComponentColorModel;
 import java.awt.image.DataBuffer;
 import java.awt.image.WritableRaster;
@@ -68,8 +67,8 @@ public final class ScaledColorSpaceTest extends ImageTestCase 
{
         assertEquals(maximum, colors.getMaxValue(0), SAMPLE_TOLERANCE);
 
         final float[] array = new float[1];
-        final double step = (maximum - minimum) / 256;
-        for (double x=minimum; x<maximum; x+=step) {
+        final double step = (maximum - minimum) / ScaledColorSpace.MAXIMUM;
+        for (double x = minimum; x < maximum; x += step) {
             array[0] = (float) x;
             assertEquals(x, colors.fromRGB(colors.toRGB(array))[0], 
2*SAMPLE_TOLERANCE);
         }
@@ -84,13 +83,13 @@ public final class ScaledColorSpaceTest extends 
ImageTestCase {
         if (viewEnabled) {
             final int transparency = Transparency.OPAQUE;
             final int datatype     = DataBuffer.TYPE_FLOAT;
-            final ColorModel model = new ComponentColorModel(colors, false, 
false, transparency, datatype);
+            final var model = new ComponentColorModel(colors, false, false, 
transparency, datatype);
             final WritableRaster data = 
model.createCompatibleWritableRaster(200, 200);
             image = new BufferedImage(model, data, false, null);
             final int width  = data.getWidth();
             final int height = data.getHeight();
             for (int x=width; --x>=0;) {
-                for (int y=height; --y>=0;) {
+                for (int y = height; --y >= 0;) {
                     double v = hypot(((double) x) / width - 0.5, ((double) y) 
/ height - 0.5);
                     v = v*(maximum - minimum) + minimum;
                     data.setSample(x, y, 0, v);
diff --git 
a/endorsed/src/org.apache.sis.portrayal/main/org/apache/sis/map/coverage/RenderingData.java
 
b/endorsed/src/org.apache.sis.portrayal/main/org/apache/sis/map/coverage/RenderingData.java
index 9ae3735684..655bc8db68 100644
--- 
a/endorsed/src/org.apache.sis.portrayal/main/org/apache/sis/map/coverage/RenderingData.java
+++ 
b/endorsed/src/org.apache.sis.portrayal/main/org/apache/sis/map/coverage/RenderingData.java
@@ -408,13 +408,12 @@ public class RenderingData implements CloneAccess {
      * @throws FactoryException if the CRS changed but the transform from old 
to new CRS cannot be determined.
      * @throws TransformException if an error occurred while transforming 
coordinates from old to new CRS.
      */
-    public final boolean ensureImageLoaded(GridCoverage coverage, final 
GridExtent sliceExtent, final boolean force)
+    public final boolean ensureImageLoaded(final GridCoverage coverage, final 
GridExtent sliceExtent, final boolean force)
             throws FactoryException, TransformException
     {
         if (!force && data != null && Objects.equals(currentSlice, 
sliceExtent)) {
             return false;
         }
-        coverage = coverage.forConvertedValues(true);
         final GridGeometry old = dataGeometry;
         final List<SampleDimension> ranges = coverage.getSampleDimensions();
         final RenderedImage image = coverage.render(sliceExtent);
@@ -550,7 +549,7 @@ public class RenderingData implements CloneAccess {
      * @return statistics on sample values for each band, in a modifiable map.
      * @throws DataStoreException if an error occurred while reading the image 
at coarsest resolution.
      */
-    protected final Map<String,Object> statistics() throws DataStoreException {
+    protected final Map<String, Object> statistics() throws DataStoreException 
{
         if (statistics == null) {
             RenderedImage image = data;
             final MultiResolutionCoverageLoader loader = coverageLoader;
@@ -560,7 +559,7 @@ public class RenderingData implements CloneAccess {
                      * If coarser data are available, we will compute 
statistics on those data instead of on the
                      * current pyramid level. We need to adjust the slice 
extent to the coordinates of coarser data.
                      */
-                    final GridCoverage coarse = 
loader.getOrLoad(0).forConvertedValues(true);
+                    final GridCoverage coarse = loader.getOrLoad(0);
                     GridExtent sliceExtent = currentSlice;
                     if (sliceExtent != null) {
                         if (sliceExtent.getDimension() <= BIDIMENSIONAL) {
@@ -577,7 +576,7 @@ public class RenderingData implements CloneAccess {
             }
             statistics = processor.valueOfStatistics(image, null, 
SampleDimensions.toSampleFilters(dataRanges));
         }
-        final var modifiers = new HashMap<String,Object>(8);
+        final var modifiers = new HashMap<String, Object>(8);
         modifiers.put("statistics", statistics);
         modifiers.put("sampleDimensions", dataRanges);
         return modifiers;
diff --git 
a/endorsed/src/org.apache.sis.storage.geotiff/main/org/apache/sis/storage/geotiff/ImageFileDirectory.java
 
b/endorsed/src/org.apache.sis.storage.geotiff/main/org/apache/sis/storage/geotiff/ImageFileDirectory.java
index e3a3b82c9e..dc740d2ba4 100644
--- 
a/endorsed/src/org.apache.sis.storage.geotiff/main/org/apache/sis/storage/geotiff/ImageFileDirectory.java
+++ 
b/endorsed/src/org.apache.sis.storage.geotiff/main/org/apache/sis/storage/geotiff/ImageFileDirectory.java
@@ -1845,17 +1845,21 @@ final class ImageFileDirectory extends DataCube {
      * May also be invoked as a fallback for image with more bands if more 
suitable color model couldn't be created.
      */
     private void createSingleBandColorModel(final Color zero, final Color 
high) throws DataStoreContentException {
-        double min = 0;
-        double max = Numerics.bitmask(bitsPerSample);   // Exclusive.
+        long min = 0;
+        long max = Numerics.bitmask(bitsPerSample) - 1;   // Inclusive.
         switch (sampleFormat) {
             default: break;
             case FLOAT:  max = 1; break;
-            case SIGNED: max /= 2; min = -max; break;
+            case SIGNED: max >>>= 1; min = ~max; break;
         }
-        if (minValues != null) min = Math.max(min, 
minValues.doubleValue(VISIBLE_BAND));
-        if (maxValues != null) max = Math.min(max, 
maxValues.doubleValue(VISIBLE_BAND) + 1);
-        colorModel = 
ColorModelFactory.createColorScale(getSampleModel(null).getDataType(),
-                        samplesPerPixel, VISIBLE_BAND, min, max, zero, high);
+        colorModel = ColorModelFactory.createColorScale(
+                getSampleModel(null).getDataType(),
+                samplesPerPixel,
+                VISIBLE_BAND,
+                (minValues == null) ? min : Math.max(min, 
minValues.doubleValue(VISIBLE_BAND)),
+                (maxValues == null) ? max : Math.min(max, 
maxValues.doubleValue(VISIBLE_BAND)),
+                zero,
+                high);
     }
 
     /**
diff --git 
a/optional/src/org.apache.sis.gui/main/org/apache/sis/gui/coverage/Stretching.java
 
b/optional/src/org.apache.sis.gui/main/org/apache/sis/gui/coverage/Stretching.java
index a312df3c38..65e2901c15 100644
--- 
a/optional/src/org.apache.sis.gui/main/org/apache/sis/gui/coverage/Stretching.java
+++ 
b/optional/src/org.apache.sis.gui/main/org/apache/sis/gui/coverage/Stretching.java
@@ -51,7 +51,7 @@ enum Stretching {
      * The initial value is {@link #NONE}.
      */
     static ChoiceBox<Stretching> createButton(final ChangeListener<Stretching> 
listener) {
-        final ChoiceBox<Stretching> button = new ChoiceBox<>();
+        final var button = new ChoiceBox<Stretching>();
         button.getItems().addAll(values());
         final SingleSelectionModel<Stretching> select = 
button.getSelectionModel();
         select.select(0);

Reply via email to