Layers · Angular, React and OpenLayers

IIIF image tiles

Render static IIIF Image API tile pyramids in OpenLayers by parsing info.json metadata, fitting pixel extents and zooming Sentinel imagery.

A Sentinel image of Kraków displayed as image tiles with an info.json address and a Load image control.
A screenshot of the example. Contains modified Copernicus Sentinel data 2024.

What this example shows

The viewer fetches an International Image Interoperability Framework (IIIF) info.json manifest describing a 2048 × 2048 pixel Sentinel satellite scene of Kraków, configures an OpenLayers tile pyramid from that document, and fits the full image cleanly inside the viewport.

An address bar and Load action let you re-read or swap the manifest URL safely: valid descriptors update the tile source and re-fit the pixel extent, while failed or superseded fetches leave the currently displayed image intact.

When you need it

Digital archives, national libraries, historical map collections and earth-observation catalogues standardise on the IIIF Image API so a single manifest describes image dimensions, scale factors and tile sizes to any compliant client.

Instead of hardcoding pyramid dimensions in frontend code, reading info.json at runtime lets one reusable map component open thousands of different scanned maps, architectural plans or satellite quicklooks while requesting only the 256-pixel regions currently in view.

The code

The example uses cc-openlayers, my Angular component library for OpenLayers: each aol-… element creates the OpenLayers object it names, updates it from its inputs and disposes of it with the component.

iiif.html
<h2>IIIF image tiles</h2>
<p class="iiif-hint">Load the local Sentinel image through IIIF image information, then zoom to inspect its tiles.</p>

<aol-map style="display: block; width: 100%" height="480px" ariaLabel="IIIF image map">
  <aol-interaction-default />
  <aol-control-defaults />
  <aol-view
    projection="EPSG:3857"
    [resolution]="image()?.resolutions?.[0] ?? 1"
    [resolutions]="image()?.resolutions"
    [extent]="image()?.extent"
    [constrainOnlyCenter]="true"
  />
  @if (image(); as loaded) {
    <aol-layer-tile>
      <aol-source-iiif [options]="loaded.options" />
    </aol-layer-tile>
  }
</aol-map>

<div class="example-controls iiif-controls">
  <form (submit)="load($event)">
    <label for="iiif-info-url">IIIF info.json URL</label>
    <input id="iiif-info-url" type="text" [value]="infoUrl()" (input)="setInfoUrl($event)" />
    <button type="submit">Load image</button>
  </form>
  @if (loading()) {
    <output role="status" aria-live="polite">Loading image information…</output>
  }
  @if (failed()) {
    <p role="alert">Could not load IIIF image information. Check the address and try again.</p>
  }
  <p class="iiif-scope-note">
    This local example supports the pre-generated image sizes and tile regions declared by its Level 0 image
    information.
  </p>
</div>
iiif.scss
.iiif-hint,
.iiif-scope-note {
  max-width: 760px;
  line-height: 1.6;
}

.iiif-controls {
  align-items: flex-start;
}

.iiif-controls form {
  display: flex;
  flex-wrap: wrap;
  align-items: center;
  gap: 8px;
}

.iiif-controls input {
  width: min(440px, 70vw);
}

.iiif-scope-note {
  flex-basis: 100%;
  margin: 0;
}

.iiif-controls [role='alert'] {
  flex-basis: 100%;
  margin: 0;
  color: var(--danger, #9b1c1c);
}
iiif.shared.ts
import IIIFInfo from 'ol/format/IIIFInfo.js';
import type { ImageInformationResponse } from 'ol/format/IIIFInfo.js';
import type { Extent } from 'ol/extent.js';
import IIIF from 'ol/source/IIIF.js';
import type { Options as IIIFOptions } from 'ol/source/IIIF.js';

/** The path is relative to the page's base URL so both root and nested static builds can load it. */
export const DEFAULT_INFO_PATH = 'assets/krakow/iiif/sentinel-krakow/info.json';

/** The stable identifier declared by the private gallery's checked-in static info document. */
export const DEFAULT_CANONICAL_ID = 'http://localhost:4200/assets/krakow/iiif/sentinel-krakow';

/** Copernicus Sentinel attribution required for reproducing the source imagery. */
export const SENTINEL_ATTRIBUTION = 'Contains modified Copernicus Sentinel data 2024';

export interface LoadedIIIFImage {
  readonly info: Record<string, unknown>;
  readonly options: IIIFOptions;
  readonly extent: Extent;
  readonly resolutions: number[];
}

export interface LoadIIIFOptions {
  /** The document base URI, injectable so the same helper works in nested static builds and tests. */
  readonly baseUri?: string;
  /** The request boundary, injectable for tests without replacing global browser fetch. */
  readonly fetchInfo?: typeof fetch;
}

/**
 * Fetch and parse a public IIIF Image API info document with OpenLayers' own parser.
 * Only the exact bundled Sentinel document is mapped from its stable canonical id to this page's
 * base-href-relative static path; any other document keeps the image id it advertises.
 */
export async function loadIIIFImage(
  infoUrl: string,
  signal: AbortSignal,
  {
    baseUri = globalThis.document?.baseURI ?? globalThis.location?.href ?? 'http://localhost/',
    fetchInfo = globalThis.fetch,
  }: LoadIIIFOptions = {}
): Promise<LoadedIIIFImage> {
  const requestUrl = new URL(infoUrl, baseUri);
  const response = await fetchInfo(requestUrl, { signal });
  if (!response.ok) throw new Error(`IIIF image information request failed (${response.status}).`);

  const info = (await response.json()) as Record<string, unknown>;
  // OpenLayers sorts the supplied scaleFactors array in place; keep the received document intact for display/tests.
  const parsed = new IIIFInfo(JSON.parse(JSON.stringify(info)) as ImageInformationResponse);
  const options = parsed.getTileSourceOptions();
  if (!options?.version || !options.size || options.size.some((value) => !Number.isSafeInteger(value) || value <= 0)) {
    throw new Error('The response does not contain valid IIIF image information.');
  }
  options.zDirection = -1;

  const bundledInfoUrl = new URL(DEFAULT_INFO_PATH, baseUri);
  const bundledLocal =
    requestUrl.origin === bundledInfoUrl.origin &&
    requestUrl.pathname === bundledInfoUrl.pathname &&
    requestUrl.search === '' &&
    requestUrl.hash === '' &&
    info['@id'] === DEFAULT_CANONICAL_ID;
  if (bundledLocal) {
    options.url = requestUrl.href.slice(0, -'info.json'.length).replace(/\/$/, '');
    options.attributions = SENTINEL_ATTRIBUTION;
    options.attributionsCollapsible = false;
  }

  const source = new IIIF({ ...options, resolutions: options.resolutions ? [...options.resolutions] : undefined });
  const tileGrid = source.getTileGrid();
  if (!tileGrid) throw new Error('The IIIF image information does not define a usable tile grid.');
  const extent = tileGrid.getExtent();
  if (!extent) throw new Error('The IIIF image information does not define a usable image extent.');
  return {
    info,
    options,
    extent,
    resolutions: tileGrid.getResolutions(),
  };
}
iiif.ts
import { isPlatformBrowser } from '@angular/common';
import {
  afterNextRender,
  ChangeDetectionStrategy,
  Component,
  DestroyRef,
  inject,
  Injector,
  PLATFORM_ID,
  signal,
  viewChild,
} from '@angular/core';
import { takeUntilDestroyed } from '@angular/core/rxjs-interop';
import {
  DefaultControlComponent,
  DefaultInteractionComponent,
  LayerTileComponent,
  MapComponent,
  SourceIIIFComponent,
  ViewComponent,
} from 'cc-openlayers';
import { catchError, defer, finalize, map, of, Subject, switchMap } from 'rxjs';
import type { LoadedIIIFImage } from './iiif.shared';
import { DEFAULT_INFO_PATH, loadIIIFImage } from './iiif.shared';

type LoadResult = { readonly image: LoadedIIIFImage } | { readonly failed: true };

/** Loads an IIIF image service document and displays the tile source described by OpenLayers. */
@Component({
  selector: 'app-iiif',
  imports: [
    DefaultControlComponent,
    DefaultInteractionComponent,
    LayerTileComponent,
    MapComponent,
    SourceIIIFComponent,
    ViewComponent,
  ],
  changeDetection: ChangeDetectionStrategy.OnPush,
  templateUrl: './iiif.html',
  styleUrl: './iiif.scss',
})
export class IIIF {
  private readonly destroyRef = inject(DestroyRef);
  private readonly injector = inject(Injector);
  private readonly browser = isPlatformBrowser(inject(PLATFORM_ID));
  private readonly mapComponent = viewChild(MapComponent);
  private readonly requests = new Subject<string>();

  protected readonly infoUrl = signal(DEFAULT_INFO_PATH);
  protected readonly image = signal<LoadedIIIFImage | null>(null);
  protected readonly loading = signal(false);
  protected readonly failed = signal(false);

  constructor() {
    this.requests
      .pipe(
        switchMap((url) => {
          const controller = new AbortController();
          this.loading.set(true);
          this.failed.set(false);
          return defer(() => loadIIIFImage(url, controller.signal)).pipe(
            map((image): LoadResult => ({ image })),
            catchError(() => of<LoadResult>({ failed: true })),
            finalize(() => controller.abort())
          );
        }),
        takeUntilDestroyed(this.destroyRef)
      )
      .subscribe((result) => {
        this.loading.set(false);
        if ('image' in result) {
          this.image.set(result.image);
          this.fitImage(result.image);
        } else {
          this.failed.set(true);
        }
      });

    if (this.browser) this.requests.next(DEFAULT_INFO_PATH);
  }

  protected setInfoUrl(event: Event): void {
    if (event.target instanceof HTMLInputElement) this.infoUrl.set(event.target.value);
  }

  protected load(event: Event): void {
    event.preventDefault();
    this.requests.next(this.infoUrl());
  }

  private fitImage(image: LoadedIIIFImage): void {
    afterNextRender(
      () => {
        if (this.image() !== image) return;
        const map = this.mapComponent()?.instance;
        if (!map) return;
        const size = map.getSize();
        map.getView().fit(image.extent, {
          size: size && size[0] > 0 && size[1] > 0 ? size : [640, 480],
        });
      },
      { injector: this.injector }
    );
  }
}

Architecture and OpenLayers mechanics

OpenLayers’ IIIFInfo parser inspects the JSON descriptor—here an Image API 2.1 Level 0 static bundle declaring 256-pixel tiles across scale factors 1, 2, 4 and 8—and generates the exact source options and custom pixel tile grid required by the IIIF tile source.

Because Level 0 compliance relies purely on pre-rendered static directories (region/size/rotation/default.jpg) rather than a dynamic cropping server, all 85 JPEG tiles are served directly from static hosting with zero backend compute. Asynchronous request tracking ensures that rapid consecutive loads discard stale responses and keep the previous image when a reload fails; only a failure on the very first load leaves the viewer empty.

How it works

  • The fixture presents a 2048 × 2048 pixel Copernicus Sentinel crop around Kraków (10 m native ground sampling) as a standards-compliant IIIF tile pyramid.
  • OpenLayers’ IIIFInfo utility parses the info.json manifest and produces the tile grid, extent and URL builder consumed by the Angular and React IIIF source adapters.
  • Declared as IIIF Image API 2 Level 0 with 256-pixel tiles at scale factors 1, 2, 4 and 8, all 85 image files are served statically without a runtime IIIF image server.
  • Manifest reloads swap the active layer source atomically after parsing succeeds, preserving the previous image if a request fails or is superseded.

Pitfalls

  • A static Level 0 IIIF pyramid only resolves the exact tile regions and scale factors listed in its info.json; arbitrary region crops or custom output widths require a dynamic Level 1 or Level 2 image server.
  • Like Zoomify, standard IIIF views run in Cartesian image pixel space rather than geographic coordinates, so coordinates read from the view represent pixels from the top-left corner rather than longitude and latitude.
  • When fetching remote info.json descriptors across domains, ensure the IIIF host sets permissive CORS headers so both the JSON fetch and canvas tile rendering succeed.

The same feature in the OpenLayers examples .

Background: state and lifecycle of maps in Angular with OpenLayers, which the components of cc-openlayers take care of.