pure ocaml image metadata library
readme.md

imgmeta #

Binary Cache:

Metadata reader for PNG, JPEG, GIF, WebP, HEIF, AVIF, TIFF, JPEG XL, BMP, ICO, and QOI. Reads "just enough" bytes to extract dimensions, depth, and orientation without decoding the image.

Put this in dune:

(libraries imgmeta)

API:

Imgmeta.of_file       : string     -> (t, error) result
Imgmeta.of_bytes      : bytes      -> (t, error) result
Imgmeta.of_in_channel : in_channel -> (t, error) result

*_exn variants are also exposed and raise Imgmeta_error on failure (see below).

match Imgmeta.of_file "photo.avif" with
| Ok { format; width; height; depth; orientation } ->
  Printf.printf "%dx%d (depth=%d, orient=%d)\n" width height depth orientation
| Error e -> Format.eprintf "%a@." Imgmeta.pp_error e

You get:

type t = {
  format      : format;  (* PNG | JPEG | GIF | WebP | HEIF | AVIF   *)
                         (* | TIFF | JXL | BMP | ICO | QOI          *)
  width       : int;     (* display width  (post-rotation)        *)
  height      : int;     (* display height (post-rotation)        *)
  depth       : int;     (* bits per channel                      *)
  orientation : int;     (* EXIF 1..8, 1 means no rotation        *)
}

width and height are the dimensions a browser will actually render. If the image carries an EXIF Orientation tag of 5/6/7/8 (or an HEIF/AVIF irot box equivalent), the dimensions are swapped from the raw pixel buffer. Use orientation if you need the original tag.

Error type:

type error =
  | Unknown_format
  | Truncated
  | Malformed of string
  | Io_error of string

depth is bits per channel. BMP and ICO count bits per pixel, which is mapped to 8 for the packed truecolour depths and reported unchanged for indexed images. A TIFF-based raw file reports what IFD0 describes, which for some camera raws is a reduced-size image rather than the full frame.

of_in_channel accepts a non-seekable channel such as a pipe, reading ahead only as far as the metadata requires.

Format detection sniffs up to the first 64 bytes, enough to read the ISOBMFF compatible brand list, and returns None for unrecognized inputs:

Imgmeta.detect_format : bytes -> format option

To test with coverage:

dune runtest --instrument-with bisect_ppx
bisect-ppx-report summary