Skip to content

Reading COGs

This guide shows how to open a Cloud Optimized GeoTIFF, read pixel windows of its levels, and work with the COGs of a directory or a glob.

The examples need a TIFF decoder on the classpath, as described in the installation section.

Open a COG

CogImage.open opens the Storage of the parent location and gets a RangeReader for the file. Closing the CogImage closes both. The call accepts a local path, or a URI with a scheme supported by tileverse-storage.

import io.tileverse.cog.CogImage;
import java.util.Properties;

Properties params = new Properties();
params.setProperty("storage.s3.region", "eu-central-1");

try (CogImage image = CogImage.open("s3://bucket/scenes/scene.tif", params)) {
    // ...
}

The Properties hold the parameters of the storage backend, for example its region, credentials, or endpoint. The storage configuration guide lists them.

To read through a RangeReader opened by your own code, pass it instead. The CogImage takes ownership of the RangeReader and closes it in close(), or when the file is rejected.

import io.tileverse.storage.RangeReader;
import io.tileverse.storage.Storage;
import io.tileverse.storage.StorageFactory;
import java.net.URI;

try (Storage storage = StorageFactory.open(URI.create("s3://bucket/scenes/"), params)) {
    RangeReader reader = storage.openRangeReader("scene.tif");
    try (CogImage image = CogImage.open(reader)) {
        // ...
    }
}

Opening a file reads its directories and checks the COG layout rules. If the file breaks one, open throws a CogVerificationException, and reason() tells which. Format support lists the reasons. For a malformed file, such as one cut short inside a directory, reason() is null.

import io.tileverse.cog.CogVerificationException;

try (CogImage image = CogImage.open(url, params)) {
    // ...
} catch (CogVerificationException e) {
    if (e.reason() == CogVerificationException.Reason.STRIPPED) {
        System.out.println("not a COG: " + e.getMessage());
    }
}

Inspect the levels

import io.tileverse.cog.CogImageSummary;

for (CogImage.Level level : image.levels()) {
    System.out.printf("level %d: %d x %d pixels, mask: %b%n",
            level.index(), level.width(), level.height(), level.hasMask());
}

CogImageSummary summary = image.summary();
System.out.printf("%d bands of %s, %s%n", summary.bands(), summary.sampleType(), summary.compressionName());
summary.epsgCode().ifPresent(code -> System.out.println("EPSG:" + code));
summary.pixelSize().ifPresent(size -> System.out.println(size.x() + " x " + size.y()));

Level 0 is the full resolution image, and the levels after it are its overviews, largest first. summary() reads nothing more from the file, because it is built from the directories read when the file was opened.

Read a window

window takes a level and a rectangle of pixels, in the pixel coordinates of that level. read() decodes those pixels.

import io.tileverse.cog.CogWindow;
import java.awt.Rectangle;
import java.awt.image.Raster;

CogWindow window = image.window(0, new Rectangle(256, 256, 512, 512));
Raster pixels = window.read();

int x = pixels.getMinX();
int y = pixels.getMinY();
int firstSample = pixels.getSample(x, y, 0);

The raster has the bands of the image, and it keeps the position of the window in the level: here getMinX() and getMinY() are both 256. If the rectangle reaches outside the level, it is clamped to the level, and the bounds of the raster tell what was read. If it misses the level altogether, window fails with an IllegalArgumentException.

The first read() fetches the tiles of the window in one batched read. That is one call to the storage, and the storage merges nearby tiles into shared requests. The window keeps the tiles in memory afterwards, and a second read() fetches nothing. Windows of more than 1,024 tiles are the exception: they fetch tile by tile, to bound their memory.

read() fails with the unchecked StorageException of the storage when a fetch fails, and with an IOException when the decoder refuses a tile.

To read at a lower resolution, ask for a window of an overview:

CogImage.Level overview = image.levels().get(2);
Rectangle whole = new Rectangle(0, 0, (int) overview.width(), (int) overview.height());
Raster thumbnail = image.window(overview.index(), whole).read();

Read the transparency mask

windowAndMask returns two windows over the same pixels: one of the level, and one of its mask. Their tiles are fetched together, in one batched read.

import java.util.Optional;

CogImage.WindowAndMask windows = image.windowAndMask(0, new Rectangle(0, 0, 512, 512));
Raster pixels = windows.pixels().read();
Optional<CogWindow> maskWindow = windows.mask();
if (maskWindow.isPresent()) {
    // One band, zero where the image has no data
    Raster mask = maskWindow.get().read();
}

mask() is empty when the level has no mask.

Use your own decoder

read() looks up a TIFF ImageReader registered with ImageIO and decodes the whole window into memory. To drive an ImageReader yourself, for example to decode into your own image type or to defer the decoding, take the TIFF stream of the window:

import java.awt.image.BufferedImage;
import javax.imageio.ImageReadParam;
import javax.imageio.ImageReader;
import javax.imageio.stream.ImageInputStream;

CogWindow window = image.window(1, new Rectangle(100, 100, 200, 200));

// reader: a TIFF ImageReader able to read BigTIFF
try (ImageInputStream stream = window.openStream()) {
    reader.setInput(stream);
    ImageReadParam param = reader.getDefaultReadParam();
    param.setSourceRegion(window.sourceRegion());
    BufferedImage decoded = reader.read(0, param);
}

The stream is a TIFF of the whole tiles under the window, and sourceRegion() locates the window inside it. Each call to openStream() opens a new stream, good for one decode.

Read the georeferencing

The module reports the EPSG code and the pixel size of a file in its summary, and leaves the rest of the georeferencing to you. openMetadataStream() returns a TIFF stream describing the full resolution image, with its tags and no pixels:

import javax.imageio.metadata.IIOMetadata;

try (ImageInputStream stream = image.openMetadataStream()) {
    reader.setInput(stream);
    // The GeoTIFF keys, the pixel scale, the tie points and the GDAL nodata value
    IIOMetadata tags = reader.getImageMetadata(0);
}

Reading it fetches nothing more from the file.

List a directory or a glob

CogLocation.parse tells what a URL names. URLs ending in a slash are directories, and URLs with a * are globs. Both parse to a CogLocation.Collection. Some URLs have neither shape and no TIFF extension, such as s3://bucket/scenes. They may name an object or a directory, and parse to a CogLocation.Probed. Format support lists the rules.

import io.tileverse.cog.collection.CogCollection;
import io.tileverse.cog.collection.CogListing;
import io.tileverse.cog.collection.CogLocation;

CogLocation location = CogLocation.parse("s3://bucket/scenes/**/*.tif", params);
if (location instanceof CogLocation.Collection container) {
    try (CogCollection collection = CogCollection.open(container, params)) {
        // Examine at most 10,000 entries, keep at most 1,000 items
        CogListing listing = collection.list(10_000, 1_000);
        for (CogCollection.Item item : listing.byId().values()) {
            System.out.println(item.id() + " at " + item.uri());
        }
        if (!listing.complete()) {
            System.out.println("the collection holds more than the bounds allow");
        }
    }
}

list takes two bounds: the most entries to examine, and the most items to keep. On object storage, listing costs one request per page of entries, whether the entries are kept or not. The bounds cap that cost before the listing starts. complete() tells whether the listing reached the end of the collection.

The id of an item is its key relative to the container: 2024/scene.tif for s3://bucket/scenes/2024/scene.tif. With an id at hand, find looks the item up with one metadata request and no listing:

Optional<CogCollection.Item> scene = collection.find("2024/scene.tif");
if (scene.isPresent()) {
    RangeReader reader = scene.get().open();
    try (CogImage image = CogImage.open(reader)) {
        // ...
    }
}

Items open through the storage of their collection. Close the image before you close the collection.

Cache what is read

The directories and tile indexes of opened files stay in the shared Tileverse metadata cache. Opening the same object again reads nothing from it until tiles are needed. The storage caches the byte ranges of the tiles when its caching parameter is on:

params.setProperty("storage.caching.enabled", "true");

CogCaches.clearAll() empties the shared caches. Format support describes them.