Why a 12-value Float32 raster breaks a GeoTIFF writer
Published · about 11 min read
There is a class of bug that survives for years because it only appears at the boundary between two well-tested libraries. geotiff.js is widely used and its reader is excellent. GDAL is the reference implementation for GeoTIFF. Between them sits a writer that, in version 2.1.3, quietly mishandles any sample wider than eight bits. The result is a file that looks like a GeoTIFF, has plausible metadata, and cannot be read.
This article takes the smallest possible failing case — a 4×3 grid, twelve Float32 deformation values — and follows it all the way down to the bytes. It then describes the tags a correct file needs, how the CRS should be declared, and the acceptance test a GDAL-based team should run before a raster is attached to a deliverable. The example is framed as a WGS 84 / UTM zone 10N product because that is a common projected CRS for North American corridor work; the same argument applies to any projected or geographic system.
Twelve numbers, two very different files
A 4×3 raster of 32-bit floating point values occupies 48 bytes of pixel data. That is not a
convention, it is arithmetic: 12 samples × 4 bytes. A TIFF IFD declares this through three
fields working together — BitsPerSample = 32,
SampleFormat = 3 (IEEE float) and
StripByteCounts = 48. A reader allocates 48 bytes, reads the strip, and interprets
each 4-byte group as a float.
In geotiff.js 2.1.3, geotiffwriter.js line 223 constructs the strip with
new Uint8Array(values). Passing a Float32Array to that constructor
does not give you a byte view of the buffer; it creates a new 8-bit array with one element per
source element, converting each float to an integer modulo 256. Twelve values become twelve
bytes. The metadata is still written correctly, so the file now claims 48 bytes of strip data
while containing 12. GDAL, QGIS and geotiff.js itself all trust the declared count, and the read
fails with Offset is outside the bounds of the DataView.
The failure is instructive because nothing about it is subtle once you look at the buffer. It is also easy to misdiagnose: the error mentions an offset, so people investigate the IFD layout, the external data area, the alignment padding. The real problem is upstream, in a single constructor call that assumed every sample is one byte.
Writing the strip the boring way
The repair is to stop going through the generic writer. Build the whole file with an
ArrayBuffer and a DataView: write II, the magic number 42
and the IFD offset; write the IFD entries; place the pixel scale, tie point and GeoKey directory
in an external data area with their offsets back-filled; then call
setFloat32(offset, value, true) once per sample. Little-endian throughout, one
band, one strip, no compression. Counting the IFD entries dynamically rather than hard-coding
them avoids the other classic GeoTIFF bug, where the declared entry count omits the GeoKey
directory tag.
That last detail matters more than it sounds. A GeoTIFF needs
ModelPixelScaleTag (33550), ModelTiepointTag (33922) and
GeoKeyDirectoryTag (34735) in addition to the ordinary image tags. If the IFD count
is wrong, readers may parse the GeoKey directory as a stray entry and discard the CRS entirely,
producing a raster that opens but lands at the origin. Writing the count from the entries array
itself removes the whole class of error.
CRS declaration is a decision, not a default
Inside the GeoKey directory, GTModelTypeGeoKey (1024) says whether the model is
projected or geographic, GTRasterTypeGeoKey (1025) says whether a pixel represents
an area or a point, and the EPSG code goes into either
ProjectedCSTypeGeoKey (3072) or GeographicTypeGeoKey (2048). A simple
classifier suffices: EPSG codes in the 4000–4999 range are geographic, codes at or above 2000
are projected, and anything smaller is invalid.
The temptation is to default to EPSG:4326 when a header is silent. That is how a raster ends
up thousands of kilometres from its vector overlay, and the mistake is often invisible because
the colour ramp still looks reasonable. A fail-closed reader reports
NO_EXPLICIT_CRS and stops. Acceptable sources are an explicit
AUTHORITY["EPSG","NNNN"] in the coordinate system string, a complete
Geographic Lat/Lon map info with WGS-84 and degrees, or a UTM map info with an
explicit zone and hemisphere. For a North American deliverable EPSG:32610 is typical; a
European one might use EPSG:32633; a global product stays in EPSG:4326. EPSG:3857 is a web
display projection and has no place in a measurement deliverable.
Reading a SNAP product without guessing
A BEAM-DIMAP product is a .dim XML file plus a .data directory.
The useful content of the XML for this purpose is the width, the height and the declared data
file path; the ENVI .hdr inside .data carries the rest: samples, lines, bands, data
type, interleave, byte order, map info and any nodata value. A careful reader takes the raw
binary selected by the declared path, then by a matching header stem, and only accepts a lone
candidate when it is genuinely the only one — .data folders routinely contain preview and
quicklook binaries that must not be mistaken for the measurement band.
Every check should be explicit. Is the interleave bsq? Is the data type one of
the supported ENVI codes? Does the binary length equal
samples × lines × bands × bytes-per-sample? Do the XML dimensions match the
header? Is the requested band inside the range? A mismatch returns a reason code the analyst can
act on. The affine transform itself comes from the 1-based reference pixel in map info:
x0 = e − (i−1)·sx, y0 = n + (j−1)·sy, with the tie point placed at
the upper-left pixel centre.
One boundary deserves emphasis: products geocoded with ground control points or a tie-point
grid do not fit a single affine transform. Reprojecting such a grid is a job for SNAP or
gdalwarp, not for a small browser encoder. Saying so in the method section is more
useful than producing a raster that is subtly warped.
An acceptance test you can paste into a ticket
Verification has two halves. In the browser, parse the generated buffer with geotiff.js,
read the band back and compute the largest absolute difference from the source values. Zero is
the only acceptable answer; anything else means the byte layout or sample format is wrong. Also
print the EPSG recovered from getGeoKeys() and the bounding box, because a raster
can be numerically perfect and geographically meaningless.
gdalinfo insar-float32.tif | grep -E "Size is|Pixel Size|Type=|AUTHORITY|Origin"
# Type=Float32 · AUTHORITY["EPSG","32610"] · Origin = (550000.0,5270000.0)
gdal_translate -of GTiff -ot Float32 -a_nodata -9999 insar-float32.tif delivered.tif
gdalinfo -stats delivered.tif | grep -E "Minimum|Maximum|Mean"
The negative north–south pixel size in gdalinfo is expected: the encoder stores
a positive sy in ModelPixelScale with a top-left tie point, which GDAL renders as a
north-up image. Note also that nodata is not written by the encoder by default; add it
explicitly if the consuming pipeline requires it, and choose a sentinel that cannot be a real
displacement.
Why this keeps happening
Most InSAR quality discussion happens at the level of phase, coherence and atmosphere. Formatting is treated as plumbing, and plumbing is exactly where a correct measurement can be destroyed without anyone noticing. A byte-level format does not have a notion of "close enough": the strip either has 48 bytes or it does not, the EPSG is either declared or it is not. The defence is not more sophisticated software but a short, repeatable check at the file boundary, run on the smallest raster that exercises the behaviour. Twelve values are enough to prove the whole chain.
| Field | Broken writer output | Correct Float32 output | How to check |
|---|---|---|---|
| BitsPerSample | 32 declared | 32 declared | gdalinfo reports Type=Float32 |
| SampleFormat (tag 339) | 3 declared | 3 declared | tiffinfo or gdalinfo |
| StripByteCounts (279) | 48 | 48 | Header value vs actual buffer length |
| Actual strip bytes | 12 | 48 | Byte count of the strip region |
| Pixel values | Truncated modulo 256 | IEEE 754 single precision | Read-back max error = 0 |
| GeoKeys | Often absent | 1024, 1025, 3072 or 2048 | gdalinfo AUTHORITY line, geotiff.js getGeoKeys() |
| Reader result | DataView offset error | Opens in GDAL, QGIS, geotiff.js | gdalinfo and a QGIS layer load |
Defect location: geotiffwriter.js line 223 in geotiff.js 2.1.3, new Uint8Array(values). Round-trip and tag behaviour verified against the local encoder in assets/js/geotiff-write.js and the vendored geotiff.js reader. EPSG:32610 is WGS 84 / UTM zone 10N; EPSG:4326 is WGS 84 geographic; EPSG:32633 is WGS 84 / UTM zone 33N.
Frequently asked questions
- Is geotiff.js 2.1.3 safe for reading Float32 GeoTIFFs?
- Yes. The defect described here is in its writer, specifically geotiffwriter.js line 223. Its reader correctly decodes Float32 strips, which is why the same library can be used both to reproduce the failure and to verify a repaired file. Many projects use geotiff.js as a reader without ever encountering this bug.
- Why does the error mention a DataView offset rather than a wrong value?
- Because the metadata and the payload disagree. StripByteCounts correctly says 48 bytes for twelve Float32 samples, but the strip region contains only 12. A reader that seeks or copies 48 bytes runs past the end of the underlying ArrayBuffer and the DataView throws before it ever reports a suspicious pixel value.
- Which GeoKey holds the EPSG code?
- ProjectedCSTypeGeoKey 3072 holds a projected code such as 32610 or 32633, while GeographicTypeGeoKey 2048 holds a geographic code such as 4326. Both sit inside the GeoKeyDirectoryTag 34735 alongside GTModelTypeGeoKey 1024 and GTRasterTypeGeoKey 1025. Writing the geographic code into the projected key, or vice versa, is a common way to produce a file that opens at the wrong location.
- Should I just convert the raster to Int16 to avoid the problem?
- That changes the data. Scaling millimetre-scale deformation to integers introduces quantisation and forces every consumer to know your scale factor, which is a new metadata dependency. Float32 preserves the measurement without a scale convention. Fix the writer instead of downgrading the samples.
- Can the browser encoder reproject my product to a UTM deliverable?
- No. It writes a single affine transform from the pixel scale and one tie point in the CRS you declare. If your product is in EPSG:4326 degrees and the deliverable requires EPSG:32610 metres, reproject first with gdalwarp -t_srs, then export, then verify the extent. Relabelling the CRS without moving coordinates is not a transformation.
- What about products geocoded with tie-point grids or GCPs?
- They are outside the scope of a single affine GeoTIFF. Terrain-corrected SNAP outputs commonly use a tie-point grid, and mapping that to one pixel scale plus one tie point requires a resampling decision. Use SNAP or GDAL to produce a conventionally geocoded raster, then hand that to the encoder.
- What belongs in a delivery note for this raster?
- At minimum: the source product and band, the EPSG and where it came from, the pixel size and upper-left tie point, the sample type, any nodata treatment, the exact gdalinfo lines showing type and AUTHORITY, and the read-back maximum error. Those six items let a third party reproduce the file years later without guessing.