### Setup Test Data Source: https://github.com/geotiffjs/geotiff.js/blob/master/README.md Run the setup script for test data after installing GDAL and ImageMagick. ```bash cd test/data sh setup_data.sh cd - ``` -------------------------------- ### Install geotiff.js via npm Source: https://github.com/geotiffjs/geotiff.js/blob/master/README.md Install the geotiff.js library into your project using npm. ```bash npm install geotiff ``` -------------------------------- ### Install GDAL and ImageMagick on MacOS Source: https://github.com/geotiffjs/geotiff.js/blob/master/README.md Install GDAL, ImageMagick, and wget on MacOS using Homebrew, required for test data setup. ```bash brew install wget gdal imagemagick ``` -------------------------------- ### Install GDAL and ImageMagick on Ubuntu Source: https://github.com/geotiffjs/geotiff.js/blob/master/README.md Install GDAL and ImageMagick on Ubuntu systems, which are required for setting up test data. ```bash sudo add-apt-repository -y ppa:ubuntugis/ubuntugis-unstable sudo apt-get update sudo apt-get install -y gdal-bin imagemagick ``` -------------------------------- ### Run Development Server Source: https://github.com/geotiffjs/geotiff.js/blob/master/README.md Start a development server for in-browser testing. Navigate to http://localhost:8090/test/ in your browser. ```bash npm run dev ``` -------------------------------- ### Example Custom Decoder Implementation Source: https://github.com/geotiffjs/geotiff.js/blob/master/_autodocs/06-compression-decoders.md An example demonstrating how to create a custom decoder by extending the BaseDecoder class. This includes handling constructor parameters and implementing the decode method for decompression and predictor application. ```javascript import { BaseDecoder } from 'geotiff'; export default class MyDecoder extends BaseDecoder { constructor(parameters) { super(parameters); // Extract parameters this.predictor = parameters.predictor; this.width = parameters.width; } async decode(buffer) { // Decompress buffer const uncompressed = decompress(buffer); // Apply predictor if needed if (this.predictor > 1) { applyPredictor(uncompressed, this.predictor, this.width); } return uncompressed; } } ``` -------------------------------- ### Install Development Dependencies Source: https://github.com/geotiffjs/geotiff.js/blob/master/README.md Install the necessary development dependencies for geotiff.js using npm. ```bash # install development dependencies npm install ``` -------------------------------- ### Initialize GeoTIFF from URL, ArrayBuffer, or Blob Source: https://github.com/geotiffjs/geotiff.js/blob/master/README.md Examples of how to initialize a GeoTIFF object from different sources: a URL, an ArrayBuffer, or a Blob. ```javascript const tiff = await fromUrl(url); ``` ```javascript const tiff = await fromArrayBuffer(buffer); ``` ```javascript const tiff = await fromBlob(blob); ``` -------------------------------- ### Performing Geospatial Calculations with GeoTIFF.js Source: https://github.com/geotiffjs/geotiff.js/blob/master/_autodocs/12-quick-reference.md Provides examples for common geospatial calculations, including getting image bounding boxes, transforming pixel coordinates to geographic coordinates, and vice versa. It also shows how to retrieve the geospatial reference system information. ```javascript // Get corners of pixel grid const [west, south, east, north] = image.getBoundingBox(); // Transform pixel to geographic const [originX, originY] = image.getOrigin(); const [resX, resY] = image.getResolution(); const geoX = originX + pixelX * resX; const geoY = originY + pixelY * resY; // Transform geographic to pixel const pixelX = (geoX - originX) / resX; const pixelY = (geoY - originY) / resY; // Get geospatial reference system const geoKeys = image.getGeoKeys(); const epsg = geoKeys?.ProjectedCSTypeGeoKey; ``` -------------------------------- ### Pool Constructor Examples Source: https://github.com/geotiffjs/geotiff.js/blob/master/_autodocs/05-pool-class.md Demonstrates creating a Pool instance with default settings, a specific number of workers, disabling pooling, or using a custom worker factory. ```javascript import { Pool } from 'geotiff'; // Use default CPU count const pool = new Pool(); // Use specific number of workers const pool2 = new Pool(4); // Disable pooling (main thread only) const noPool = new Pool(0); // Use custom worker function createWorker() { return new Worker(new URL('./my-decoder-worker.js', import.meta.url)); } const customPool = new Pool(4, createWorker); ``` -------------------------------- ### Get a Decoder Instance - Deflate Source: https://github.com/geotiffjs/geotiff.js/blob/master/_autodocs/06-compression-decoders.md Use `getDecoder` to obtain an instance for a specific compression type. This example retrieves the decoder for Deflate compression (ID 8). ```javascript import { getDecoder } from 'geotiff'; const decoder = await getDecoder(8); // Deflate const decoded = await decoder.decode(compressedBuffer); ``` -------------------------------- ### Get Decoder Parameters and Instance Source: https://github.com/geotiffjs/geotiff.js/blob/master/_autodocs/06-compression-decoders.md Use `getDecoderParameters` to extract compression-specific parameters from the image file directory, then use these parameters with `getDecoder` to instantiate the correct decoder. ```javascript import { getDecoderParameters } from 'geotiff'; const compression = image.fileDirectory.getValue('Compression'); const params = await getDecoderParameters(compression, image.fileDirectory); const decoder = await getDecoder(compression, params); ``` -------------------------------- ### Reference: Quick Reference Source: https://github.com/geotiffjs/geotiff.js/blob/master/_autodocs/README.md A quick reference guide for common patterns and tasks in geotiff.js, including loading, reading, writing, geospatial calculations, and performance optimization. ```APIDOC ## Reference: Quick Reference ### Description Common patterns and quick lookup. ### Topics - Loading GeoTIFF files. - Reading raster data (simple, windowed, with resampling, etc.). - Geospatial calculations. - Writing GeoTIFF files. - Error handling examples. - Performance optimization tips. - v2 → v3 migration guide. ``` -------------------------------- ### Add a Basic Custom Decoder Source: https://github.com/geotiffjs/geotiff.js/blob/master/_autodocs/06-compression-decoders.md Register a custom decoder for a specific compression ID using `addDecoder`. This example shows how to add a basic LZW decoder without custom parameters. ```javascript import { addDecoder } from 'geotiff'; import MyLZWDecoder from './my-lzw.js'; addDecoder(4, () => Promise.resolve(MyLZWDecoder)); ``` -------------------------------- ### Load GeoTIFF Files from Various Sources Source: https://github.com/geotiffjs/geotiff.js/blob/master/_autodocs/12-quick-reference.md Demonstrates how to load GeoTIFF files using different methods: from a URL, an ArrayBuffer, a Blob/File in the browser, or a file path in Node.js. Includes an example for loading with external overviews for Cloud Optimized GeoTIFFs. Remember to close the TIFF file when done. ```javascript import { fromUrl, fromArrayBuffer, fromBlob, fromFile, fromUrls } from 'geotiff'; // From HTTP URL const tiff = await fromUrl('https://example.com/dem.tif'); // From ArrayBuffer (JavaScript) const response = await fetch('data.tif'); const buffer = await response.arrayBuffer(); const tiff = await fromArrayBuffer(buffer); // From Blob/File (browser) const file = document.getElementById('fileInput').files[0]; const tiff = await fromBlob(file); // From file path (Node.js) const tiff = await fromFile('/path/to/file.tif'); tiff.close(); // Don't forget to close! // With external overviews (Cloud Optimized GeoTIFF) const multiTiff = await fromUrls('main.tif', ['main.tif.ovr']); ``` -------------------------------- ### Add a Custom Decoder with Parameters Source: https://github.com/geotiffjs/geotiff.js/blob/master/_autodocs/06-compression-decoders.md Register a custom decoder with a parameter extractor function. This example demonstrates how to dynamically import the decoder and extract custom parameters from the file directory. ```javascript import { addDecoder, defaultDecoderParameterFn } from 'geotiff'; addDecoder( 12345, // Custom compression ID () => import('./custom-decoder.js').then(m => m.default), async (fileDirectory) => { const baseParams = await defaultDecoderParameterFn(fileDirectory); return { ...baseParams, myCustomParam: await fileDirectory.loadValue('MyCustomTag') }; } ); ``` -------------------------------- ### Example: Type Usage in GeoTIFF Processing Source: https://github.com/geotiffjs/geotiff.js/blob/master/_autodocs/09-types-and-interfaces.md Demonstrates how to use GeoTIFF types and interfaces to load a GeoTIFF, configure raster reading options, and process the results. Includes imports for necessary components and asynchronous handling. ```typescript import { GeoTIFF, GeoTIFFImage, Pool, ReadRastersOptions } from 'geotiff'; async function processGeoTIFF(url: string): Promise { const tiff: GeoTIFF = await fromUrl(url); const image: GeoTIFFImage = await tiff.getImage(); const options: ReadRastersOptions = { window: [0, 0, 512, 512], samples: [0, 1, 2], interleave: false, resampleMethod: 'bilinear', pool: new Pool(4) }; const result = await image.readRasters(options); // result: TypedArrayArrayWithDimensions const [band0, band1, band2] = result; console.log(`Size: ${result.width}x${result.height}`); } ``` -------------------------------- ### Core API: Compression Decoders Source: https://github.com/geotiffjs/geotiff.js/blob/master/_autodocs/README.md Provides a system for handling compression codecs. Allows getting, extracting parameters for, and adding custom decoders. ```APIDOC ## Core API: Compression Decoders ### Description Compression codec system. ### Methods - `getDecoder(compression)`: Get decoder instance. - `getDecoderParameters(compression, fileDirectory)`: Extract decoder parameters. - `addDecoder(id, factory, paramExtractor)`: Register custom decoders. - `BaseDecoder` class — Custom decoder base class. - Supported compressions and custom implementations. ``` -------------------------------- ### ReadRasterResult Usage Examples Source: https://github.com/geotiffjs/geotiff.js/blob/master/_autodocs/09-types-and-interfaces.md Illustrates how to access pixel data and dimensions from ReadRasterResult, depending on whether bands are interleaved or non-interleaved. ```javascript const data = await image.readRasters({ interleave: true }); const pixel0 = data[0]; // First value const { width, height } = data; ``` ```javascript const data = await image.readRasters({ interleave: false }); const [band0, band1, band2] = data; const { width, height } = data; ``` -------------------------------- ### Conditional Image Reading Based on Photometric Interpretation Source: https://github.com/geotiffjs/geotiff.js/blob/master/_autodocs/10-configuration-and-globals.md Demonstrates how to determine an image's photometric interpretation and perform different actions based on its value. This example shows reading RGB data or loading a color map for palette-based images. ```javascript import { photometricInterpretations, fromUrl } from 'geotiff'; const tiff = await fromUrl('image.tif'); const image = await tiff.getImage(); const photoInterp = image.fileDirectory.getValue('PhotometricInterpretation'); if (photoInterp === photometricInterpretations.RGB) { const rgb = await image.readRGB(); } else if (photoInterp === photometricInterpretations.Palette) { const colorMap = await image.fileDirectory.loadValue('ColorMap'); } ``` -------------------------------- ### Request Specific Bands for Performance Source: https://github.com/geotiffjs/geotiff.js/blob/master/_autodocs/12-quick-reference.md Improve performance by requesting only the necessary bands from the GeoTIFF image. This example demonstrates how to read only band 3. ```javascript // Request only needed bands const [nir] = await image.readRasters({ samples: [3] // Only band 3 }); ``` -------------------------------- ### Basic GeoTIFF Loading and Reading Source: https://github.com/geotiffjs/geotiff.js/blob/master/_autodocs/README.md Load a GeoTIFF file from a URL, get an image, read its metadata (width, height, bands), and then read all raster data. This snippet demonstrates the core workflow for accessing GeoTIFF data. ```javascript import { fromUrl } from 'geotiff'; // Load a GeoTIFF const tiff = await fromUrl('https://example.com/dem.tif'); // Get the first image const image = await tiff.getImage(); // Read metadata console.log(`Size: ${image.getWidth()}x${image.getHeight()}`); console.log(`Bands: ${image.getSamplesPerPixel()}`); // Read all raster data const data = await image.readRasters(); const [band0, band1, band2] = data; console.log(`Read: ${data.width}x${data.height}`); ``` -------------------------------- ### Write GeoTIFF with Multiple Strips Source: https://github.com/geotiffjs/geotiff.js/blob/master/README.md Create a GeoTIFF with multiple strips by specifying `RowsPerStrip` and `StripByteCounts` in the metadata. This example demonstrates interleaving RGB data. ```javascript const originalRed = [ [255, 255, 255], [0, 0, 0], [0, 0, 0], ]; const originalGreen = [ [0, 0, 0], [255, 255, 255], [0, 0, 0], ]; const originalBlue = [ [0, 0, 0], [0, 0, 0], [255, 255, 255], ]; const interleaved = originalRed.flatMap((row, rowIdx) => row.flatMap((value, colIdx) => [ value, originalGreen[rowIdx][colIdx], originalBlue[rowIdx][colIdx], ])); const values = new Uint8Array(interleaved); const metadata = { height: 3, width: 3, RowsPerStrip: 1, StripByteCounts: [9, 9, 9], }; const newGeoTiffAsBinaryData = await writeArrayBuffer(values, metadata); ``` -------------------------------- ### Register Custom LERC+Deflate Decoder Source: https://github.com/geotiffjs/geotiff.js/blob/master/_autodocs/06-compression-decoders.md Example of registering a custom decoder for a specific compression type (LERC with Deflate). This involves providing a unique ID, a function to load the decoder module, and a function to extract decoder parameters from the file directory. ```javascript import { addDecoder, getDecoderParameters } from 'geotiff'; // Register custom LERC+Deflate decoder addDecoder( 34888, // LERC with Deflate () => import('./lerc-deflate.js').then(m => m.default), async (fileDirectory) => { const params = await getDecoderParameters(34887, fileDirectory); // LERC params return { ...params, // Add custom parameters lercMask: await fileDirectory.loadValue('LercMask'), innerCompression: 8 // Deflate }; } ); ``` -------------------------------- ### Optimize GeoTIFF Performance with Worker Pool Source: https://github.com/geotiffjs/geotiff.js/blob/master/_autodocs/12-quick-reference.md Utilize a worker pool for faster processing of compressed images. This example shows how to create a pool and use it when reading rasters. ```javascript import { Pool } from 'geotiff'; // Use worker pool for compressed images const pool = new Pool(4); const data = await image.readRasters({ pool }); ``` -------------------------------- ### Handle Network Errors with fromUrl Source: https://github.com/geotiffjs/geotiff.js/blob/master/_autodocs/11-errors.md Catch and handle network-related errors, such as 404s or CORS issues, when loading GeoTIFF files from a URL using `fromUrl`. This example checks for TypeError indicating a fetch-related problem. ```javascript try { const tiff = await fromUrl('https://example.com/missing.tif'); } catch (error) { if (error instanceof TypeError && error.message.includes('fetch')) { console.error('Network error or CORS issue'); } } ``` -------------------------------- ### Read GeoTIFF at Specific Resolution Source: https://github.com/geotiffjs/geotiff.js/blob/master/_autodocs/12-quick-reference.md Optimize reading by specifying desired resolution (resX, resY). The library will automatically select the best overview level if available. This example also shows how to specify a bounding box. ```javascript // Read at appropriate resolution const tiff = await fromUrl('cog.tif'); const data = await tiff.readRasters({ bbox: [10, 50, 20, 60], resX: 10, // Automatically selects best overview resY: 10 }); ``` -------------------------------- ### Run Tests Source: https://github.com/geotiffjs/geotiff.js/blob/master/README.md Execute the library tests using npm, which utilizes PhantomJS, karma, mocha, and chai. ```bash npm test ``` -------------------------------- ### getTag() Source: https://github.com/geotiffjs/geotiff.js/blob/master/_autodocs/10-configuration-and-globals.md Gets the full tag definition for a tag name or ID. ```APIDOC ## getTag() ### Description Gets the full tag definition for a tag name or ID. ### Method ```javascript getTag(tagIdentifier: string | number): TagDictionary | undefined ``` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters - **tagIdentifier** (string | number) - Required - Tag name or numeric ID ### Response #### Success Response (200) - **tagDictionary** (TagDictionary | undefined) - TagDictionary entry or undefined if not found. ### Response Example ```javascript import { getTag } from 'geotiff'; const widthTag = getTag('ImageWidth'); if (widthTag) { console.log(`Tag ${widthTag.tag}: ${widthTag.name}`); console.log(`Type: ${widthTag.type}, Eager: ${widthTag.eager}`); } ``` ``` -------------------------------- ### Get Image Height Source: https://github.com/geotiffjs/geotiff.js/blob/master/_autodocs/03-geotiffimage-class.md Retrieves the height of the image in pixels. This is a fundamental property of the image. ```javascript getHeight(): number ``` -------------------------------- ### Get Image Width Source: https://github.com/geotiffjs/geotiff.js/blob/master/_autodocs/03-geotiffimage-class.md Retrieves the width of the image in pixels. This is a fundamental property of the image. ```javascript getWidth(): number ``` -------------------------------- ### Writing Basic GeoTIFF Files Source: https://github.com/geotiffjs/geotiff.js/blob/master/_autodocs/12-quick-reference.md Illustrates how to write basic GeoTIFF files using `writeArrayBuffer`. This includes creating simple images, RGB images, and GeoTIFFs with georeferencing information. ```javascript import { writeArrayBuffer } from 'geotiff'; // Basic image const values = new Uint8Array([1, 2, 3, 4, 5, 6, 7, 8, 9]); const buffer = writeArrayBuffer(values, { width: 3, height: 3 }); // RGB image const buffer = writeArrayBuffer(values, { width: 100, height: 100, SamplesPerPixel: 3, PhotometricInterpretation: 2 // RGB }); // GeoTIFF with georeferencing const buffer = writeArrayBuffer(values, { width: 1000, height: 1000, BitsPerSample: 16, ModelPixelScale: [30, 30, 0], ModelTiepoint: [0, 0, 0, 500000, 4500000, 0], ProjectedCSTypeGeoKey: 32632 // UTM Zone 32N }); ``` -------------------------------- ### getSamplesPerPixel() Source: https://github.com/geotiffjs/geotiff.js/blob/master/_autodocs/03-geotiffimage-class.md Returns the number of samples (bands/channels) per pixel. For example, RGB images return 3. ```APIDOC ## getSamplesPerPixel() ### Description Returns the number of samples (bands/channels) per pixel. For example, RGB images return 3. ### Method ```javascript getSamplesPerPixel(): number ``` ### Returns - **number** - The number of samples per pixel. ``` -------------------------------- ### Build the Library Source: https://github.com/geotiffjs/geotiff.js/blob/master/README.md Build the geotiff.js library for browser and Node.js environments. Output files are located in dist-browser/main.js and dist-node/main.js. ```bash npm run build ``` -------------------------------- ### Get Image Origin Source: https://github.com/geotiffjs/geotiff.js/blob/master/_autodocs/03-geotiffimage-class.md Retrieves the geographic coordinates [X, Y] of the top-left pixel. This is derived from ModelTiepoint or ModelTransformation tags. ```javascript const [x, y] = image.getOrigin(); console.log(`Top-left corner: (${x}, ${y})`); ``` -------------------------------- ### Get File Directory Source: https://github.com/geotiffjs/geotiff.js/blob/master/_autodocs/03-geotiffimage-class.md Retrieves the raw ImageFileDirectory object, which contains all parsed TIFF tags for direct access. ```javascript getFileDirectory(): ImageFileDirectory ``` -------------------------------- ### Get Tile Width Source: https://github.com/geotiffjs/geotiff.js/blob/master/_autodocs/03-geotiffimage-class.md Retrieves the width of each tile for tiled images, or the full image width for stripped images. ```javascript getTileWidth(): number ``` -------------------------------- ### Constructor Source: https://github.com/geotiffjs/geotiff.js/blob/master/_autodocs/07-multigeotiff-class.md Creates a new MultiGeoTIFF instance from a main GeoTIFF file and an array of overview GeoTIFF files. It's recommended to use the `fromUrls()` factory function for creating MultiGeoTIFF objects. ```APIDOC ## Constructor ```javascript constructor(mainFile: GeoTIFF, overviewFiles: GeoTIFF[]) ``` Creates a new MultiGeoTIFF from main and overview GeoTIFF files. ### Parameters - **mainFile** (GeoTIFF) - Required - The main (highest resolution) GeoTIFF. - **overviewFiles** (GeoTIFF[]) - Required - Array of overview GeoTIFF files in ascending resolution order. **Note**: Normally use `fromUrls()` factory function instead of constructing directly. ### Example ```javascript import { fromUrl, MultiGeoTIFF } from 'geotiff'; const mainFile = await fromUrl('data.tif'); const overview = await fromUrl('data.tif.ovr'); const multiTiff = new MultiGeoTIFF(mainFile, [overview]); ``` ``` -------------------------------- ### Get Tile Height Source: https://github.com/geotiffjs/geotiff.js/blob/master/_autodocs/03-geotiffimage-class.md Retrieves the height of each tile for tiled images, or the row height per strip for stripped images. ```javascript getTileHeight(): number ``` -------------------------------- ### fromUrls() Source: https://github.com/geotiffjs/geotiff.js/blob/master/_autodocs/01-geotiff-factory-functions.md Loads a GeoTIFF with external overview/pyramid files, commonly used for Cloud Optimized GeoTIFF (COG) files with separate overview files. It supports specifying multiple URLs for the main file and its overviews. ```APIDOC ## fromUrls() ### Description Loads a GeoTIFF with external overview/pyramid files. Used for Cloud Optimized GeoTIFF (COG) files with separate overview files (.ovr). ### Method `fromUrls(mainUrl: string, overviewUrls?: string[], options?: SourceOptions, signal?: AbortSignal): Promise` ### Parameters #### Path Parameters - **mainUrl** (string) - Yes - URL to the main GeoTIFF file - **overviewUrls** (string[]) - No - URLs to overview/pyramid files - **options** (SourceOptions) - No - Source options (see fromUrl) - **signal** (AbortSignal) - No - AbortSignal to cancel the operation ### Response #### Success Response - **MultiGeoTIFF** - Promise resolving to a MultiGeoTIFF instance (which supports the same image access as GeoTIFF). ### Request Example ```javascript import { fromUrls } from 'geotiff'; const multiTiff = await fromUrls( 'LC08_L1TP_189027_20170403_20170414_01_T1_B3.TIF', ['LC08_L1TP_189027_20170403_20170414_01_T1_B3.TIF.ovr'] ); const image = await multiTiff.getImage(); ``` ``` -------------------------------- ### Instantiate MultiGeoTIFF with GeoTIFF objects Source: https://github.com/geotiffjs/geotiff.js/blob/master/_autodocs/07-multigeotiff-class.md Use this constructor to create a MultiGeoTIFF instance when you already have GeoTIFF objects for the main and overview files. It's recommended to use the `fromUrls()` factory function for simpler URL-based instantiation. ```typescript import { fromUrl, MultiGeoTIFF } from 'geotiff'; const mainFile = await fromUrl('data.tif'); const overview = await fromUrl('data.tif.ovr'); const multiTiff = new MultiGeoTIFF(mainFile, [overview]); ``` -------------------------------- ### getDecoder() Source: https://github.com/geotiffjs/geotiff.js/blob/master/_autodocs/06-compression-decoders.md Gets a decoder instance for the specified compression type. It can be used to retrieve decoders for built-in compression methods or custom-added ones. ```APIDOC ## getDecoder() ### Description Gets a decoder instance for the specified compression type. ### Method Signature ```javascript async getDecoder(compression: number, decoderParameters?: BaseDecoderParameters): Promise ``` ### Parameters #### Path Parameters * **compression** (number) - Required - TIFF compression ID * **decoderParameters** (BaseDecoderParameters) - Optional - Optional decoder-specific parameters ### Returns Promise resolving to a BaseDecoder instance. ### Throws Error if decoder not found or registration failed. ### Example ```javascript import { getDecoder } from 'geotiff'; const decoder = await getDecoder(8); // Deflate const decoded = await decoder.decode(compressedBuffer); ``` ``` -------------------------------- ### Load GeoTIFF with Overviews from URLs Source: https://github.com/geotiffjs/geotiff.js/blob/master/_autodocs/01-geotiff-factory-functions.md Use `fromUrls` to load a GeoTIFF, optionally providing URLs for external overview/pyramid files. This is useful for Cloud Optimized GeoTIFFs (COGs) with separate overview files. ```javascript import { fromUrls } from 'geotiff'; const multiTiff = await fromUrls( 'LC08_L1TP_189027_20170403_20170414_01_T1_B3.TIF', ['LC08_L1TP_189027_20170403_20170414_01_T1_B3.TIF.ovr'] ); const image = await multiTiff.getImage(); ``` -------------------------------- ### Get Image Bounding Box Source: https://github.com/geotiffjs/geotiff.js/blob/master/_autodocs/03-geotiffimage-class.md Retrieves the geographic bounding box [minX, minY, maxX, maxY] of the image, representing its spatial coverage. ```javascript const [west, south, east, north] = image.getBoundingBox(); console.log(`Coverage: ${west}, ${south} to ${east}, ${north}`); ``` -------------------------------- ### Accessing Geotiff.js Globals Source: https://github.com/geotiffjs/geotiff.js/blob/master/_autodocs/10-configuration-and-globals.md Demonstrates how to import and access various constants and utilities from the 'globals' namespace in geotiff.js. ```javascript import { globals } from 'geotiff'; // All of the above are accessible via globals: globals.fieldTypes globals.photometricInterpretations globals.tagDictionary globals.geoKeyNames globals.geoKeys // etc. ``` -------------------------------- ### Reading GeoTIFF with ModelTiepoint/ModelPixelScale (v2 vs v3) Source: https://github.com/geotiffjs/geotiff.js/blob/master/README.md Demonstrates reading `ModelPixelScale` and `ModelTiepoint` tags. v3 requires using `getValue()` for synchronous access. ```javascript const tiff = await fromUrl(url); const image = await tiff.getImage(); const { ModelPixelScale: s, ModelTiepoint: t } = image.fileDirectory; const [sx, sy, sz] = s; const [px, py, k, gx, gy, gz] = t; ``` ```javascript const tiff = await fromUrl(url); const image = await tiff.getImage(); const s = image.fileDirectory.getValue('ModelPixelScale'); const t = image.fileDirectory.getValue('ModelTiepoint'); const [sx, sy, sz] = s; const [px, py, k, gx, gy, gz] = t; ``` -------------------------------- ### Get Samples Per Pixel Source: https://github.com/geotiffjs/geotiff.js/blob/master/_autodocs/03-geotiffimage-class.md Retrieves the number of samples (e.g., color channels) per pixel. For RGB images, this will return 3. ```javascript getSamplesPerPixel(): number ``` -------------------------------- ### loadValue() Source: https://github.com/geotiffjs/geotiff.js/blob/master/_autodocs/04-imagefiledirectory-class.md Gets the value of a TIFF tag asynchronously, loading deferred values on-demand. Use this for large arrays that may not be eagerly loaded. ```APIDOC ## loadValue() ### Description Gets the value of a TIFF tag asynchronously, loading deferred values on-demand. Use this for large arrays that may not be eagerly loaded. ### Parameters #### Path Parameters - **tagNameOrId** (string | number) - Required - Tag name or numeric tag ID ### Returns Promise resolving to the tag value. ### Example ```javascript // For potentially large arrays, use loadValue const colorMap = await image.fileDirectory.loadValue('ColorMap'); const tileOffsets = await image.fileDirectory.loadValue('TileOffsets'); const stripOffsets = await image.fileDirectory.loadValue('StripOffsets'); // For small values, getValue is fine const photoInterp = image.fileDirectory.getValue('PhotometricInterpretation'); ``` ``` -------------------------------- ### Writing a Tiled GeoTIFF Image Source: https://github.com/geotiffjs/geotiff.js/blob/master/_autodocs/08-write-geotiff.md This snippet demonstrates writing a GeoTIFF image with tiles. Pixel data should be organized by tile, and metadata must include `TileWidth`, `TileLength`, and `TileByteCounts`. Partial tiles are zero-padded. ```javascript import { writeArrayBuffer } from 'geotiff'; // Create 3×3 image with 2×2 tiles const width = 3, height = 3; const tileWidth = 2, tileHeight = 2; const samplesPerPixel = 3; // Tile data (4 tiles, pad partial tiles with zeros) // Tile layout: [TL, TR, BL, BR] with partial tiles zero-padded const values = new Uint8Array([ // Tile 1 (top-left, 2x2) 255, 0, 0, 255, 0, 0, 255, 0, 0, 255, 0, 0, // Tile 2 (top-right, 2x2 with padding) 255, 0, 0, 0, 0, 0, 255, 0, 0, 0, 0, 0, // Tile 3 (bottom-left, 2x2 with padding) 0, 255, 0, 0, 255, 0, 0, 0, 0, 0, 0, 0, // Tile 4 (bottom-right, 2x2 with padding) 0, 255, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, ]); const metadata = { width: 3, height: 3, SamplesPerPixel: 3, BitsPerSample: 8, PhotometricInterpretation: 2, // RGB TileWidth: tileWidth, TileLength: tileHeight, TileByteCounts: [12, 12, 12, 12] // 4 bytes × 3 samples per pixel }; const buffer = writeArrayBuffer(values, metadata); ``` -------------------------------- ### Get total image count from MultiGeoTIFF Source: https://github.com/geotiffjs/geotiff.js/blob/master/_autodocs/07-multigeotiff-class.md Obtain the total number of images available across all combined files (main and overview files). ```typescript const multiTiff = await fromUrls('main.tif', ['main.tif.ovr']); const totalImages = await multiTiff.getImageCount(); console.log(`Total images: ${totalImages}`); ``` -------------------------------- ### Get the Total Number of Images in a GeoTIFF Source: https://github.com/geotiffjs/geotiff.js/blob/master/_autodocs/02-geotiff-class.md Returns the total count of images (IFDs) present in the GeoTIFF file. Useful for iterating through all images. ```javascript const count = await tiff.getImageCount(); for (let i = 0; i < count; i++) { const image = await tiff.getImage(i); console.log(`Image ${i}: ${image.getWidth()}x${image.getHeight()}`); } ``` -------------------------------- ### Write GeoTIFF to File or Server Source: https://github.com/geotiffjs/geotiff.js/blob/master/_autodocs/08-write-geotiff.md Demonstrates how to write the generated GeoTIFF buffer to a file in Node.js, trigger a download in the browser, or send it to a server via fetch. ```javascript // Node.js: Write to file import fs from 'fs'; const buffer = writeArrayBuffer(values, metadata); fs.writeFileSync('output.tif', Buffer.from(buffer)); ``` ```javascript // Browser: Download file const blob = new Blob([buffer], { type: 'image/tiff' }); const url = URL.createObjectURL(blob); const a = document.createElement('a'); a.href = url; a.download = 'output.tif'; a.click(); ``` ```javascript // Browser: Send to server const formData = new FormData(); formData.append('file', new Blob([buffer], { type: 'image/tiff' })); await fetch('/upload', { method: 'POST', body: formData }); ``` -------------------------------- ### Get GeoTIFF Image by Index Source: https://github.com/geotiffjs/geotiff.js/blob/master/README.md Retrieve a specific image from the GeoTIFF file using its index. Defaults to the first image. This operation is asynchronous. ```javascript const image = await tiff.getImage(); // by default, the first image is read. ``` -------------------------------- ### Using Geotiff.js RGB Utilities Source: https://github.com/geotiffjs/geotiff.js/blob/master/_autodocs/10-configuration-and-globals.md Shows how to import and use the convenience functions from the 'rgb' module for color space conversions, primarily used internally by readRGB(). ```javascript import { rgb } from 'geotiff'; // Internal conversions used by readRGB(): rgb.fromWhiteIsZero() rgb.fromBlackIsZero() rgb.fromPalette() rgb.fromCMYK() rgb.fromYCbCr() rgb.fromCIELab() ``` -------------------------------- ### Not Implemented Error Example Source: https://github.com/geotiffjs/geotiff.js/blob/master/_autodocs/11-errors.md This error is thrown by base class methods that require implementation in subclasses. Avoid calling methods directly on GeoTIFFBase instances. ```javascript Error: Not implemented ``` -------------------------------- ### getValue() Source: https://github.com/geotiffjs/geotiff.js/blob/master/_autodocs/04-imagefiledirectory-class.md Gets the value of a TIFF tag synchronously. Values for common tags are eagerly loaded. Throws an error if the tag is deferred and not yet loaded. ```APIDOC ## getValue() ### Description Gets the value of a TIFF tag synchronously. For most common tags (dimensions, compression, etc.), values are eagerly loaded. **Throws**: Error if the tag is deferred and not yet loaded. ### Parameters #### Path Parameters - **tagNameOrId** (string | number) - Required - Tag name (e.g., 'ImageWidth') or numeric tag ID ### Returns The tag value, or `undefined` if not present. ### Example ```javascript const width = image.fileDirectory.getValue('ImageWidth'); const height = image.fileDirectory.getValue('ImageLength'); const compression = image.fileDirectory.getValue('Compression'); ``` ``` -------------------------------- ### Import GeoTIFF Module Source: https://github.com/geotiffjs/geotiff.js/blob/master/README.md Import the GeoTIFF library using require or import statements. ```javascript const GeoTIFF = require('geotiff'); const { fromUrl, fromUrls, fromArrayBuffer, fromBlob } = GeoTIFF; ``` ```javascript import GeoTIFF, { fromUrl, fromUrls, fromArrayBuffer, fromBlob } from 'geotiff'; ``` -------------------------------- ### Get GeoTIFF Image Count and Specific Image Source: https://github.com/geotiffjs/geotiff.js/blob/master/README.md Retrieve the total number of images within a GeoTIFF file and access a specific image by its index. ```javascript const imageCount = await tiff.getImageCount(); ``` ```javascript const image = await tiff.getImage(index); ``` -------------------------------- ### fromCustomClient Source: https://github.com/geotiffjs/geotiff.js/blob/master/_autodocs/01-geotiff-factory-functions.md Loads a GeoTIFF using a custom HTTP client implementation, allowing advanced control over HTTP requests. ```APIDOC ## fromCustomClient() ### Description Loads a GeoTIFF using a custom HTTP client implementation. Allows advanced control over HTTP requests. ### Method `fromCustomClient(client: BaseClient, options?: SourceOptions, signal?: AbortSignal): Promise` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters Table | Parameter | Type | Required | Default | Description | |-----------|------|----------|---------|-------------| | client | BaseClient | Yes | — | A custom HTTP client implementing BaseClient interface | | options | SourceOptions | No | {} | Source options | | signal | AbortSignal | No | — | AbortSignal to cancel the operation | ### Returns Promise resolving to a GeoTIFF instance. ### Example ```javascript import { fromCustomClient, BaseClient } from 'geotiff'; class MyCustomClient extends BaseClient { async request(url, headers) { // Custom implementation } } const client = new MyCustomClient(); const tiff = await fromCustomClient(client); ``` ``` -------------------------------- ### getImage() Source: https://github.com/geotiffjs/geotiff.js/blob/master/_autodocs/07-multigeotiff-class.md Retrieves a GeoTIFFImage from any of the combined files (main and overviews) based on a sequential index. Images are indexed across all files starting from the main file. ```APIDOC ## getImage() ```javascript getImage(index?: number): Promise ``` Gets an image from any of the combined files (main + overviews). Images are indexed sequentially across all files. ### Parameters - **index** (number) - Optional - Default: 0 - Zero-based image index across all files. ### Returns Promise resolving to a GeoTIFFImage instance. ### Throws RangeError if index is out of bounds. ### Example ```javascript const multiTiff = await fromUrls('main.tif', ['main.tif.ovr']); // Get first image from main file const mainImage = await multiTiff.getImage(0); // If main file has multiple images, this gets the second one const secondMainImage = await multiTiff.getImage(1); // First image from overview file (if main file has 1 image) const overviewImage = await multiTiff.getImage(2); ``` ``` -------------------------------- ### Include geotiff.js via CDN Source: https://github.com/geotiffjs/geotiff.js/blob/master/README.md Include the prebuilt version of geotiff.js in your HTML file using a CDN link. ```html ``` -------------------------------- ### Access TIFF Tag Dictionary Entry Source: https://github.com/geotiffjs/geotiff.js/blob/master/_autodocs/10-configuration-and-globals.md Import the tagDictionary from 'geotiff' to access metadata for standard TIFF tags. This example shows how to retrieve the entry for 'ImageWidth'. ```javascript import { tagDictionary } from 'geotiff'; const entry = tagDictionary.ImageWidth; // { // tag: 256, // name: 'ImageWidth', // type: 3, // SHORT // eager: true // } ``` -------------------------------- ### Create MultiGeoTIFF from URLs Source: https://github.com/geotiffjs/geotiff.js/blob/master/_autodocs/07-multigeotiff-class.md Instantiate a MultiGeoTIFF object by providing the URL of the main GeoTIFF file and an array of URLs for its overview files. ```javascript import { fromUrls } from 'geotiff'; const multiTiff = await fromUrls( 'https://example.com/LC08_B3.TIF', ['https://example.com/LC08_B3.TIF.ovr'] ); ``` -------------------------------- ### Reference: Configuration and Globals Source: https://github.com/geotiffjs/geotiff.js/blob/master/_autodocs/README.md Global configuration options and constants for geotiff.js, including logging, tag registration, and references for various constants like field types and compressions. ```APIDOC ## Reference: Configuration and Globals ### Description Global configuration and constants. ### Methods - `setLogger(logger)`: Configure logging. - `registerTag(name, definition)`: Register custom TIFF tags. - `resolveTag(id)`: Tag ID/name conversion. - `getTag(id)`: Get tag definition. - Complete constant references: field types, photometric interpretations, sample formats, compressions. - `geoKeyNames`, `geoKeys` — GeoTIFF metadata keys. ``` -------------------------------- ### Core API: Factory Functions Source: https://github.com/geotiffjs/geotiff.js/blob/master/_autodocs/README.md Entry point functions for loading GeoTIFF files from various sources. These functions provide convenient ways to access GeoTIFF data based on the input format. ```APIDOC ## Core API: Factory Functions ### Description Entry point functions for loading GeoTIFF files. ### Methods - `fromUrl(url, options)`: Load from HTTP URL. - `fromArrayBuffer(arrayBuffer, options)`: Load from binary data. - `fromBlob(blob, options)`: Load from browser File/Blob. - `fromFile(filePath, options)`: Load from disk (Node.js). - `fromUrls(urls, options)`: Load with external overviews. - `fromCustomClient(client, options)`: Custom HTTP implementation. ``` -------------------------------- ### Get Image Resolution Source: https://github.com/geotiffjs/geotiff.js/blob/master/_autodocs/03-geotiffimage-class.md Retrieves the pixel size in geographic units [X, Y], typically derived from the ModelPixelScale tag. The Y resolution is usually negative for north-up images. ```javascript const [resX, resY] = image.getResolution(); console.log(`Pixel size: ${Math.abs(resX)} x ${Math.abs(resY)} units`); ``` -------------------------------- ### Enable Caching for Tile Reading Source: https://github.com/geotiffjs/geotiff.js/blob/master/_autodocs/README.md If you are repeatedly reading the same tiles, enable caching using the `cache: true` option to speed up subsequent reads. ```javascript cache: true ``` -------------------------------- ### Get GeoTIFF GeoKeys Source: https://github.com/geotiffjs/geotiff.js/blob/master/_autodocs/03-geotiffimage-class.md Retrieves parsed GeoTIFF geospatial keys. Returns null if no geospatial metadata is present. Useful for determining coordinate system information. ```javascript const image = await tiff.getImage(); const geoKeys = image.getGeoKeys(); if (geoKeys && geoKeys.ProjectedCSTypeGeoKey) { console.log(`EPSG:${geoKeys.ProjectedCSTypeGeoKey}`); } ``` -------------------------------- ### Use Appropriate Resolution Source: https://github.com/geotiffjs/geotiff.js/blob/master/_autodocs/README.md For multiresolution files, specify the desired resolution using `resX` and `resY` to read rasters efficiently. ```javascript readRasters({ resX, resY }) ``` -------------------------------- ### Async getTiePoints() and getGDALMetadata() (v2 vs v3) Source: https://github.com/geotiffjs/geotiff.js/blob/master/README.md In v3, `getTiePoints()` and `getGDALMetadata()` are now asynchronous and require `await`. Ensure these calls are properly awaited. ```javascript const tiePoints = image.getTiePoints(); const metadata = image.getGDALMetadata(); ``` ```javascript const tiePoints = await image.getTiePoints(); const metadata = await image.getGDALMetadata(); ``` -------------------------------- ### Constructor Source: https://github.com/geotiffjs/geotiff.js/blob/master/_autodocs/05-pool-class.md Creates a new decoder pool with a specified number of workers. You can configure the pool size or provide a custom worker factory. ```APIDOC ## Constructor ```javascript constructor(size?: number, createWorker?: () => Worker) ``` Creates a new decoder pool with the specified number of workers. ### Parameters - **size** (number) - Optional - Number of worker threads. Set to 0 or null to disable pooling (decode in main thread). Defaults to navigator.hardwareConcurrency or 2 if unavailable. - **createWorker** (() => Worker) - Optional - Function that creates Worker instances. Defaults to a built-in worker. ### Returns Pool instance. ### Example ```javascript import { Pool } from 'geotiff'; // Use default CPU count const pool = new Pool(); // Use specific number of workers const pool2 = new Pool(4); // Disable pooling (main thread only) const noPool = new Pool(0); // Use custom worker function createWorker() { return new Worker(new URL('./my-decoder-worker.js', import.meta.url)); } const customPool = new Pool(4, createWorker); ``` ``` -------------------------------- ### Load GeoTIFF from Custom Client Source: https://github.com/geotiffjs/geotiff.js/blob/master/_autodocs/01-geotiff-factory-functions.md Use `fromCustomClient` to load a GeoTIFF with a custom HTTP client. This is useful for advanced control over network requests. Ensure your custom client implements the `BaseClient` interface. ```javascript import { fromCustomClient, BaseClient } from 'geotiff'; class MyCustomClient extends BaseClient { async request(url, headers) { // Custom implementation } } const client = new MyCustomClient(); const tiff = await fromCustomClient(client); ``` -------------------------------- ### Render GeoTIFF Data with Plotty Source: https://github.com/geotiffjs/geotiff.js/blob/master/README.md Use the Plotty library to render GeoTIFF raster data on an HTML canvas. This example shows how to fetch GeoTIFF data from a URL and display it. ```html ``` -------------------------------- ### Custom Decoder Implementation (v2 vs v3) Source: https://github.com/geotiffjs/geotiff.js/blob/master/README.md v3 custom decoders require a constructor that accepts parameters and a `decode` method that takes only the buffer. Parameter extraction is handled externally. ```javascript class MyDecoder extends BaseDecoder { async decode(fileDirectory, buffer) { // decode using fileDirectory properties } } ``` ```javascript class MyDecoder extends BaseDecoder { constructor(parameters) { super(parameters); // parameters extracted once during construction } async decode(buffer) { // decode using this.parameters } } // Register with parameter extraction function addDecoder( 12345, // compression ID () => import('./mydecoder.js').then(m => m.default), async (fileDirectory) => { return { ...await defaultDecoderParameterFn(fileDirectory), myCustomParam: await fileDirectory.loadValue('MyCustomTag') }; } ); ``` -------------------------------- ### Get an image from MultiGeoTIFF Source: https://github.com/geotiffjs/geotiff.js/blob/master/_autodocs/07-multigeotiff-class.md Retrieve a specific image from any of the combined GeoTIFF files (main and overviews). Images are indexed sequentially across all files. An out-of-bounds index will result in a RangeError. ```typescript const multiTiff = await fromUrls('main.tif', ['main.tif.ovr']); // Get first image from main file const mainImage = await multiTiff.getImage(0); // If main file has multiple images, this gets the second one const secondMainImage = await multiTiff.getImage(1); // First image from overview file (if main file has 1 image) const overviewImage = await multiTiff.getImage(2); ``` -------------------------------- ### Clone geotiff.js Repository Source: https://github.com/geotiffjs/geotiff.js/blob/master/README.md Clone the geotiff.js repository from GitHub to your local machine. ```bash # clone repo git clone https://github.com/constantinius/geotiff.js.git cd geotiff.js/ ``` -------------------------------- ### Get a Specific GeoTIFF Image by Index Source: https://github.com/geotiffjs/geotiff.js/blob/master/_autodocs/02-geotiff-class.md Retrieves a specific image (IFD) from a GeoTIFF file using its zero-based index. Most files contain a single image at index 0. ```javascript const tiff = await fromUrl('data.tif'); const image = await tiff.getImage(); // Get first image const image2 = await tiff.getImage(1); // Get second image ``` -------------------------------- ### SourceOptions Interface Source: https://github.com/geotiffjs/geotiff.js/blob/master/_autodocs/09-types-and-interfaces.md Configuration options for remote data sources, used with functions like `fromUrl` and `fromUrls`. ```APIDOC ## Interface: SourceOptions ### Description Options for remote sources (`fromUrl`, `fromUrls`). ### Type Definition ```typescript interface SourceOptions { headers?: Record // HTTP headers maxRanges?: number // Max ranges per request (0 = disabled) allowFullFile?: boolean // Allow full file responses forceXHR?: boolean // Use XMLHttpRequest instead of Fetch blockSize?: number // Cache block size cacheSize?: number // Number of blocks to cache } ``` ``` -------------------------------- ### Get Common TIFF Tag Values Synchronously Source: https://github.com/geotiffjs/geotiff.js/blob/master/_autodocs/04-imagefiledirectory-class.md Use getValue() for common, eagerly loaded TIFF tags like dimensions and compression. This method retrieves values synchronously. ```javascript const width = image.fileDirectory.getValue('ImageWidth'); const height = image.fileDirectory.getValue('ImageLength'); const compression = image.fileDirectory.getValue('Compression'); ``` -------------------------------- ### Get GeoTIFF Image Properties Source: https://github.com/geotiffjs/geotiff.js/blob/master/README.md Retrieve essential properties of a GeoTIFF image, including dimensions, samples per pixel, tile dimensions, origin, resolution, and bounding box. ```javascript const width = image.getWidth(); ``` ```javascript const height = image.getHeight(); ``` ```javascript const samplesPerPixel = image.getSamplesPerPixel(); ``` ```javascript const tileWidth = image.getTileWidth(); ``` ```javascript const tileHeight = image.getTileHeight(); ``` ```javascript const origin = image.getOrigin(); ``` ```javascript const resolution = image.getResolution(); ``` ```javascript const bbox = image.getBoundingBox(); ``` -------------------------------- ### Pool Initialization with Custom Worker Factory Source: https://github.com/geotiffjs/geotiff.js/blob/master/_autodocs/05-pool-class.md Create a Pool with a specified number of workers and a factory function to create custom decoder workers. This allows for advanced decompression logic. ```javascript import { Pool } from 'geotiff'; function createWorker() { return new Worker(new URL('./my-custom-decoder.js', import.meta.url)); } const pool = new Pool(4, createWorker); const data = await image.readRasters({ pool }); ```