geotiffjs / geotiff.js

geotiff.js is a small library to parse TIFF files for visualization or analysis. It is written in pure JavaScript, and is usable in both the browser and node.js applications.
https://geotiffjs.github.io/
MIT License
878 stars 183 forks source link

Small files are not being read properly from URL #319

Open LaPommeCosmique opened 2 years ago

LaPommeCosmique commented 2 years ago

Explanation

This issue occurs in nodejs when using fromUrl() to read small files ( < 4 kB) from a remote source.

The problem can be found in /src/source/client/http.js, line 58

const data = Buffer.concat(chunks).buffer;

In the code above: chunks is an array of nodejs <Buffer> objects that stores the data from the remote source Buffer.concat(chunks) concatenates the array of <Buffer> objects into one big <Buffer> object Buffer.concat(chunks).buffer obtains the underlying <Array Buffer> object, which is necessary because that's what geotiff.js uses

The problem is that the underlying <Array Buffer> object may contain more bytes that the nodejs <Buffer> object exposes. This occurs when the length of the <Buffer> object is less than half the pool size (4 kB). As a result, we may be saving additional bytes that do not belong to the tiff source, which will throw off the geotiff interpreter.

Solution

Replacing the previous code with the code below will fix the problem. The code below extracts only the data that belongs to the tiff file.

const concat = Buffer.concat(chunks);
const data = concat.buffer.slice (concat.byteOffset, concat.byteOffset + concat.byteLength)

Relevant stackoverflow here