Search code examples
javascripttypescripthdf5gdal

Write new dataset from 2d array in node-gdal-async


I am trying to create a new dataset from a 2d array in JavaScript. However, I can't seem to find my way around the docs to do this.

To create a new dataset, I seem to have to use gdal.open in write mode to be able to write new data, but I am unsure how to update this empty raster with my real data:

const driver = gdal.drivers.get('GTiff');
const xSize = 3;
const ySize = 3;
const bandCount = 1;
const dataType = gdal.GDT_Int32;
const dataset = await gdal.openAsync('output.tif', 'w', driver, xSize, ySize, bandCount, dataType);

Now let's say I have the following 2D array of data:

// from a hdf5 file
const data = [
    [1, 2, 3],
    [4, 5, 6],
    [7, 8, 9],
];

How would I update my dataset to have the provided data?


Solution

  • Here is the correct code snippet:

    const xSize = 3;
    const ySize = 3;
    const bandCount = 1;
    const dataType = gdal.GDT_Int32;
    const dataset = await gdal.openAsync('output.tif', 'w', 'GTiff', xSize, ySize, bandCount, dataType);
    
    const data = new Int32Array([
        1, 2, 3,
        4, 5, 6,
        7, 8, 9,
    ]);
    
    const band1 = await dataset.bands.getAsync(1);
    await band1.pixels.writeAsync(0, 0, xSize, ySize, data);
    await dataset.flushAsync();
    

    A few notes:

    • This is the fully async code, meaning you will never block the event loop;

    • gdal requires that you use TypedArrays. If you want to use multidimensional arrays, I suggest you consider using ndarray and scijs, there is also a plugin for gdal-async;

    • There is no closeAsync, but if you call flushAsync you guarantee that the data will be written, even if the file won't be closed until the GC destroys the object.