Skip to content

About

A JavaScript Exif info parser.

Resources

Code of conduct

Contributing

Security policy

Stars

1.0k stars

Watchers

12 watching

Forks

Latest commit

 

History

1,142 Commits

Folders and files

NameName
Last commit message
Last commit date
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

ExifReader

ExifReader is a JavaScript library that parses image files and extracts the metadata. It can also extract an embedded thumbnail. It can be used either in a browser or from Node. Supports JPEG, JPEG XL, TIFF, PNG, HEIC, AVIF, WebP, and GIF files with Exif, IPTC, XMP, ICC, MPF, and more metadata (depending on file type).

If you use the length: 'auto' option, ExifReader reads only the bytes that contain metadata, well under 1 ms per file for typical phone JPEGs and over 95% less bandwidth.

You can compose a reader from only the formats, groups and tags you read. A reader of the date and the GPS position of JPEG files bundles to about 12 KiB (esbuild, minified, Brotli). See the composable API.

ExifReader supports module formats ESM, AMD, CommonJS, and globals and can therefore easily be used from Webpack, RequireJS, Browserify, Node etc.

You can try it out on the examples site.

Support table

File type Exif IPTC XMP ICC MPF Photoshop MakerNote Thumbnail Image details
JPEG yes yes yes yes yes some* some** yes yes
JPEG XL*** yes yes**** yes some**** N/A some* some** yes yes
TIFF yes yes yes yes N/A some* some** yes N/A
PNG yes yes yes yes N/A some* some** yes yes
HEIC/HEIF yes yes**** yes yes N/A some* some** yes yes
AVIF yes yes**** yes yes N/A some* some** yes yes
WebP yes yes**** yes yes N/A some* some** yes yes
GIF N/A N/A N/A N/A N/A N/A N/A N/A yes
  • MakerNote = Manufacturers' proprietary MakerNote tags.
  • Image details = image width, height, etc. read from image header.
  • N/A = The feature is not applicable to this file type.
  • * = A draft implementation of Photoshop tags have been added with ClippingPathName and PathInformation currently supported. Photoshop tags are very different from other tags and need a lot of extra code so they have deliberately not been fully implemented. File an issue if there is something you think should really be supported.
  • ** = Some of the Canon-specific and Pentax-specific tags have been added. File an issue if you think something more should be supported.
  • *** = Metadata in JPEG XL are often (but not always) encoded with Brotli compression. This is supported in some environments when using async: true. See the Asynchronous tags and Custom decompression sections for details. JPEG XL defines no MPF block. A JPEG recompressed to JPEG XL keeps its MPF segment only in its JPEG reconstruction data, which ExifReader does not read.
  • **** = Read from the Exif data, where the IPTC-NAA and ICC_Profile tags can carry them, in the same way as for TIFF files. The HEIC/HEIF, AVIF and WebP formats define no IPTC block of their own. The ICC profile inside a JPEG XL codestream is not read.

If you're missing something that you think should be supported, file an issue with an attached example image and I'll see what I can do.

Table of Contents

  1. Support
  2. Installation
  3. Usage
  4. Configure a Custom Build (deprecated)
  5. Notes
  6. Client/Browser Support
  7. Examples
  8. Tips
  9. Known Limitations
  10. Contributing
  11. Code of Conduct
  12. License
  13. Changelog

Support

Monetary support is not necessary for me to continue working on this, but in case you like this library and want to support its development you are very welcome to click the button below. You can also use GitHub's sponsor feature on the right-hand side on the repository's main page.

Buy me a coffee

Installation

Easiest is through npm or Bower:

npm install exifreader --save
bower install exifreader --save

If you want to clone the git repository instead:

git clone git@github.com:mattiasw/ExifReader.git
cd ExifReader
npm install

After that, the transpiled, concatenated and minified ES5 file will be in the dist folder together with a sourcemap file.

Type definitions

Type definitions for TypeScript are included in the package. Each subpath of the composable API (exifreader/core, exifreader/formats, exifreader/groups, exifreader/tags/exif and exifreader/tags/iptc) ships its own definitions next to its module, which TypeScript finds with moduleResolution set to bundler, node16 or nodenext. A CommonJS file can import them only with module set to nodenext or node20 (see Toolchains in the composable API). exifreader/core also exports the types of the arguments to load, LoadInput and LoadOptions, and of its result, Tags and ExpandedTags.

Usage

Importing

NOTE: See React Native instructions below.

ES module syntax:

import ExifReader from 'exifreader';

NOTE: TypeScript/Angular seems to sometimes have problems when using the default export. If you're seeing issues, use this syntax instead:

import * as ExifReader from 'exifreader';

CommonJS/Node modules:

const ExifReader = require('exifreader');

AMD modules:

requirejs(['/path/to/exif-reader.js'], function (ExifReader) {
    ...
});

script tag:

<script src="/path/to/exif-reader.js"></script>

In a browser app? If you only need a few tags, compose a reader with only what you read. This one reads the date and the GPS position of JPEG files:

import {createReader} from 'exifreader/core';
import {jpeg} from 'exifreader/formats';
import {gps} from 'exifreader/groups';
import {DateTimeOriginal} from 'exifreader/tags/exif';

const reader = createReader({formats: [jpeg], groups: [gps], tags: [DateTimeOriginal]});
const tags = await reader.load(file);
// tags.exif.DateTimeOriginal, tags.gps.Latitude, tags.gps.Longitude

It bundles to about 12 KiB, against about 42 KiB for the default entry (esbuild, minified, Brotli). See the composable API for the rest. For everything else, start with the default entry as shown above.

Loading tags

There are two ways to load the tags. Either have ExifReader do the loading of the image file, or load the file yourself first and pass in the file buffer. The main difference is that the first one is asynchronous and the second one is synchronous unless specified.

Let ExifReader load the file (asynchronous API)

const tags = await ExifReader.load(file);
const imageDate = tags['DateTimeOriginal'].description;
const unprocessedTagValue = tags['DateTimeOriginal'].value;

Where file is one of

  • File object, the result of a form file upload (browser)
  • File path on a local file system (Node.js)
  • URL (browser or Node.js; remember that in a browser context the remote server has to set CORS headers that allow for remote loading of the file)

Security: When the argument is a string, ExifReader treats it as a URL or a local file path and will make a network request or read from the file system. Never pass an untrusted or user-controlled string to load(). Doing so lets an attacker make the process fetch arbitrary URLs (server-side request forgery) or open arbitrary local files. For untrusted image data, always pass the bytes themselves (an ArrayBuffer, a typed array such as Uint8Array or Buffer, or a browser File), never a string.

Tip: To read metadata from an HTMLImageElement, wait for its load event and call ExifReader.load(image.src). The browser should reuse the cached file.

Load the file yourself (synchronous API)

const tags = ExifReader.load(fileBuffer);

Where fileBuffer is one of

  • ArrayBuffer or SharedArrayBuffer (browser, Node.js)
  • any typed array such as Uint8Array, or a DataView (browser, Node.js)
  • Buffer (Node.js)

See the examples site for more directions on how to use the library.

Security: Treat all returned metadata as untrusted input. Tag values, descriptions, and the raw XMP packet (xmp._raw when using expanded: true) come straight from the image and can contain arbitrary text, including HTML-like markup. Never insert them into a page as HTML (for example through innerHTML) without escaping or sanitizing them first, otherwise a crafted image could lead to cross-site scripting. Use textContent, your framework's escaping, or a sanitizer such as DOMPurify when displaying metadata.

The property names inside a tag value come from the image too, and a tag whose name is __proto__ is kept under that name as a regular property, so it does not replace the prototype of the object holding it. A tag whose name comes from the image and is the name of an Object.prototype method, such as hasOwnProperty, toString or constructor, is returned under that name with _ appended (hasOwnProperty_), so it does not hide the method on the result object or on a group object, and includeTags and excludeTags match it by that returned name. The same applies to the property names inside an XMP tag value (structure members, members of list items and children of rdf:value) and to the keys of an XMP tag's attributes. A value parsed from an XMP rdf:value element that holds child elements other than a list is returned as an object without a prototype. An XMP qualifier in attributes that holds child elements is returned as its element tree, with the element and attribute names unchanged and kept in objects without a prototype. Such an object has no inherited methods, and copying it into an object of your own with Object.assign or a deep merge helper without filtering the keys could let a crafted image replace that object's prototype.

Grouping

By default, Exif, IPTC and XMP tags are grouped together. This means that if e.g. Orientation exists in both Exif and XMP, the first value (Exif) will be overwritten by the second (XMP). If you need to separate between these values, pass in an options object with the property expanded set to true:

const tags = ExifReader.load(fileBuffer, {expanded: true});

Filtering tags (includeTags / excludeTags)

You can filter which tags are returned by using includeTags and/or excludeTags.

  • If includeTags is provided, it uses an include-pattern: only the groups you specify will be included in the output.
  • excludeTags can be used alone to remove tags/groups while keeping everything else.
  • If a group is specified in both includeTags and excludeTags, excludeTags for that group will be ignored.
  • An empty selector array (e.g. includeTags: { xmp: [] }) is treated as excluding that group. The group will not be returned and ExifReader will skip parsing it.
  • A group's value can be true, an array of selectors, or false to leave the group out. That is useful with a boolean variable, e.g. includeTags: { exif: true, xmp: includeXmp }.

Examples

Exclude a few tags in the Exif group:

const tags = ExifReader.load(fileBuffer, {
    excludeTags: {
        exif: ['MakerNote', 0x9286],
    }
});

Only return XMP tags (and exclude everything else):

const tags = ExifReader.load(fileBuffer, {
    includeTags: {
        xmp: true,
    }
});

Filtering groups

The group keys follow the same concept as the output when expanded: true is used. (The thumbnail group controls the top-level thumbnail value.)

For PNG, filtering is done with the png group only. (The pngFile and pngText groups exist in expanded output today, but png is the filtering key and those groups will be deprecated later.)

Group key Description Supports IDs
exif Exif tags (including GPS IFD, interoperability). yes
iptc IPTC tags. yes
xmp XMP tags. no
icc ICC profile tags. no
photoshop Photoshop resource tags. yes
makerNotes MakerNote tags (e.g. Canon/Pentax). yes
mpf MPF tags. yes
file JPEG file details, image details of JPEG XL, HEIC/HEIF and AVIF, and FileType. no
jfif JFIF tags. no
png PNG header, chunk, and text tags. no
riff WebP (RIFF) tags. no
gif GIF tags. no
gps Computed GPS group (only when expanded: true). no
composite Composite tags (e.g. FieldOfView). no
thumbnail Top-level thumbnail output. no

Important: dependency tags

Some tags act as pointers or containers to other metadata. Excluding them can cause other tags or entire groups to disappear. Some important examples:

  • Exif IFD Pointer, GPS Info IFD Pointer, Interoperability IFD Pointer
  • IPTC-NAA (Exif embedded IPTC), ApplicationNotes (Exif embedded XMP), ICC_Profile (Exif embedded ICC)
  • MakerNote and Make (maker note parsing)
  • ImageSourceData and PhotoshopSettings (Photoshop parsing)
  • JPEGInterchangeFormat and JPEGInterchangeFormatLength (thumbnails)

NOTE: When using includeTags, you do not have to list these dependency tags. ExifReader will automatically include the required pointer/container tags needed to find and parse the groups you requested. This section mainly matters when using excludeTags.

Note that XMP and ICC tags are parsed from full metadata blocks, so ExifReader cannot skip parsing individual XMP/ICC tags based on selectors. The returned output is still filtered.

Filtering removes parsed tags only, not the raw data they were parsed from. Some tags hold such data, for example xmp._raw (with expanded: true), the Exif ApplicationNotes and IPTC-NAA tags, the MPF Images, PNG text tags and thumbnail. When filtering for privacy, list the tags you want in includeTags (by name, not true) instead of excluding the ones you do not.

Unknown tags

Tags that are unknown, either because they have been excluded by making a custom build or they are yet to be added into ExifReader, are by default not included in the output. If you need to see them there is an option that can be passed in:

const tags = ExifReader.load(fileBuffer, {includeUnknown: true});

If you discover an unknown tag that should be handled by ExifReader, please reach out by filing an issue.

Computed tag values (opt-in)

ExifReader exposes three different values per Exif tag:

  • value: A stable, raw-ish value that mirrors how the tag is stored in the file.
  • description: A human-friendly value meant for display.
  • computed: An opt-in, type-aware value. This will often be the same as value except for RATIONAL/SRATIONAL and ASCII tags.

Enable the computed value by passing computed: true in the options:

const tags = ExifReader.load(fileBuffer, {computed: true});

const make = tags['Make'].computed; // e.g. "Apple"
const xResolution = tags['XResolution'].computed; // e.g. 72

computed is only added for tags parsed from TIFF IFD structures (Exif/GPS/etc, including maker notes, MPF, and the Thumbnail IFD). It is not currently added to XMP/IPTC/ICC tags or PNG text tags.

The computed conversion rules are based on the TIFF tag type:

  • ASCII: If value contains a single string, computed is that string. Otherwise computed is a string array.
  • RATIONAL / SRATIONAL: computed is a number (or an array of numbers). Division by zero yields null.
  • All other types: computed equals value.

Note that computed may evolve in minor versions as the feature matures. If you need a value with the strongest stability guarantees, prefer value.

Read only part of file

If you only want to read part of the image file you can use the length option:

const tags = await ExifReader.load(filename, {length: 128 * 1024});

This will load only the first 128 KiB of the file. This could be useful if you know the metadata is located at the beginning of the file. Just be aware that it's common for the metadata to be spread out over a larger area so please try it out on your set of files to know if it's suitable for your situation.

One thing to look out for is ICC profiles, which are often large. If the profile does not fit inside the part you read, no ICC tags are returned for it. Use length: 'auto' (see below) if you need the ICC tags without picking a size yourself.

Note that this option only works when ExifReader handles the loading of the file. If e.g. an already loaded ArrayBuffer, typed array or Buffer is passed into ExifReader, the whole file will already have been loaded into memory and it's too late. More specifically the length option will work for 1. local files when running through Node.js, 2. remote files when passing a URL, and 3. browser File objects (e.g., from form file fields). For remote files accessed through a web browser, make sure the remote server is either on the same origin (domain) as your script or that the server is passing correct CORS headers, specifically allowing the Range header.

For those inputs a fractional length is rounded down, and a length that is not a finite non-negative number or 'auto' (such as the string '1024', NaN, Infinity or a negative number) makes load() reject before anything is read.

Read only the metadata bytes (length: 'auto')

When you want to download or store just enough of an image to extract its metadata, without guessing a fixed length, pass length: 'auto':

const tags = await ExifReader.load(url, {
    length: 'auto',
    expanded: true,
    includeOffsets: true,
    excludeTags: {mpf: true},  // skip embedded preview; see note below
});

tags.metadataRange.end       // exact byte count needed for the metadata
tags.metadataRange.buffer    // bytes [0, end), sliced from what we read.
                             //   Same kind as the input (ArrayBuffer,
                             //   SharedArrayBuffer or Node Buffer). For a
                             //   typed array or DataView input it is an
                             //   ArrayBuffer (a SharedArrayBuffer when the
                             //   view is over one) holding only the view's
                             //   bytes. Save this to disk to keep only the
                             //   metadata-bearing prefix.
tags.metadataRange.fetched   // bytes actually read. May be greater than
                             //   `end` because the loop reads in fixed-size
                             //   chunks and so may read a little past `end`.
tags.metadataRange.requests  // number of IO calls performed

ExifReader fetches an initial 128 KiB prefix and parses it. Only if the metadata extends further does it issue an HTTP Range request (or a follow-up filesystem read / File.slice) for exactly the additional bytes needed. Most files finish in a single request. HEIC/AVIF files where the Exif/XMP iloc entries point near the end of the file typically take two.

length: 'auto' is supported for the four IO inputs:

  • URL via browser fetch (uses HTTP Range)
  • URL via Node http(s) (uses HTTP Range)
  • Local file path via Node fs
  • Browser File object via File.slice

It is also accepted for in-memory inputs (ArrayBuffer, SharedArrayBuffer, Node.js Buffer, any other typed array and DataView) as a convenience. There is no IO loop to run in that case, but metadataRange.buffer is still attached as the trimmed slice of what you passed in.

Requirements and caveats:

  • expanded: true and includeOffsets: true are required. Passing length: 'auto' without them throws a clear error (at runtime, and also a type error in TypeScript).
  • The return is always a Promise because the loop is asynchronous.
  • Not supported for plain TIFF or bare JPEG XL codestreams. They have no leading metadata container, so the loop has no convergence signal and will reject with an error.
  • If the loop fails to converge in 4 iterations (very rare, defensive bound for unknown-size HTTP responses or files whose parsers can't bootstrap from a small prefix), ExifReader reads the rest of the file and emits a single console.warn. Correctness is preserved. The bandwidth savings are forfeit.

Why excludeTags: {mpf: true} is in the example. Most modern phone cameras (and many DSLRs) emit JPEGs with a Multi-Picture-Format sub-image preview embedded a few MB into the file. Without excludeTags: {mpf: true} ExifReader treats those sub-images as part of the metadata range, so metadataRange.end lands near EOF and length: 'auto' ends up reading most of the file anyway. On a corpus of about 1.5 GiB of phone photos this single option took length: 'auto' from a ~17% slowdown vs a regular full read to a 6× speedup with 98% of bytes saved. The regular tags.exif, tags.xmp, tags.icc, tags.gps and the rest are unaffected. Drop the option only if you actually need the tags.mpf.Images array.

Locating metadata in the file (includeOffsets)

Pass includeOffsets: true together with expanded: true to learn where in the file the metadata sits. Useful for persisting only the metadata-bearing prefix of an image rather than the whole file. The resulting slice is enough for re-extracting metadata with ExifReader, not for opening the slice as an image.

const tags = ExifReader.load(fileBuffer, {expanded: true, includeOffsets: true});

tags.metadataRange.start    // lowest block start (informational, can be deep
                            //   into the file for HEIC/AVIF; do NOT use as a
                            //   slice boundary, always slice from 0)
tags.metadataRange.end      // exclusive end. Store bytes 0..end to keep all metadata
tags.metadataRange.complete // false when the input was truncated before all metadata
tags.metadataRange.blocks   // [{type, start, end}, ...] sorted by start

Offsets are byte indices into the data you passed in. metadataRange is attached only when both expanded: true and includeOffsets: true are set, so default and flat-mode output are unchanged.

Block type reuses the filtering-group vocabulary (exif, iptc, xmp, icc, mpf, jfif, file, png, riff, gif), plus mpfImage for the sub-images of an MPF Multi-Picture JPEG. The same type may appear more than once (multi-chunk ICC, extended XMP), one entry per physical container. ExifReader records at most 4,096 of the containers it finds while scanning the file; in a file with more, the last one recorded keeps its own type and is widened to cover all the rest, so start, end and the 0..end slice still cover every metadata byte. mpfImage blocks come on top of these.

Typical workflow:

const headChunk = await fetchFirstNBytes(url, 256 * 1024);
const tags = ExifReader.load(headChunk, {expanded: true, includeOffsets: true});

if (!tags.metadataRange.complete) {
    // 256 KiB was not enough, fetch more
} else {
    const minimalSlice = headChunk.slice(0, tags.metadataRange.end);
    await uploadMetadata(minimalSlice);
}

Notes and limitations:

  • Not supported for plain TIFF or bare JPEG XL codestreams (no leading metadata container). metadataRange is omitted in both cases.
  • For JPEG XL containers, blocks cover the Exif and xml boxes but not the jxlc/jxlp codestream box (encoded image data, not metadata).
  • complete: true means ExifReader did not detect truncation. For JPEG and PNG it observed SOS or IEND, for standalone XMP it observed an <?xpacket end=?> or </x:xmpmeta> token. For other formats it is best-effort, a buffer ending cleanly between metadata segments can still report complete: true. Non-standard trailers (JPEG-XT, post-SOS markers) are never detected. Note the converse: re-parsing a slice produced by buffer.slice(0, metadataRange.end) may report complete: false for JPEG/PNG even though every metadata segment is intact, because the slice ends before SOS/IEND. The block list and tags.exif etc. are still complete in that case.
  • Only the metadata segments ExifReader actively parses are present in blocks. JPEG segments ExifReader does not currently extract tags from (APP3-APP12, COM comments, JPEG-XT extensions) do not appear and are not guaranteed to be preserved by a 0..end slice. The slice is enough to re-extract everything ExifReader itself reads, not to preserve every byte a third-party tool might care about.
  • For HEIC/AVIF, metadata can sit near the end of the file, so metadataRange.end often lands close to the file size and trimming saves little. The icc block here covers just the ICC profile bytes; for JPEG/PNG/WebP it covers the full container wrapper.
  • For MPF JPEGs, sub-images appear as mpfImage blocks and push end toward the file size. If MPF parsing is suppressed by a tag filter (any excludeTags: {mpf: ...} or includeTags that does not include mpf), the mpfImage blocks are not emitted and metadataRange.end shrinks. The parent mpf segment block always remains, since it is a real metadata segment found during the header scan.
  • Offsets come from length fields in the file. Treat metadataRange.end and block.end as untrusted input. Clamp to your buffer length before slicing, allocating, or issuing remote range requests.

Asynchronous tags

Some tags need to be parsed asynchronously. Currently this is the case for some PNG tags (compressed tags in zTXt, iTXt, and iCCP chunks) and JPEG XL files with Brotli-compressed metadata (very common). To enable this, either use the asynchronous API mentioned above or pass in async: true in the options parameter:

const tags = await ExifReader.load(file);
// or
const tags = await ExifReader.load(fileBuffer, {async: true});

For the compressed PNG tags to work, the environment needs to support the Compression Streams API. Most modern browsers support deflate decompression through this API.

For JPEG XL Brotli decompression, Firefox, Safari, and Node.js have built-in support through the Compression Streams API. Chrome does not currently support Brotli in its Compression Streams API (April 2026). For environments without built-in Brotli support, you can provide a custom decompression function via the decompress option (see below).

The reason for having an option to enable asynchronous parsing is to not break backwards compatibility. This will probably be the default in the next major version.

Custom decompression

You can provide custom decompression functions for Brotli and/or deflate via the decompress option. This is useful for JPEG XL files with Brotli-compressed metadata in environments that don't have built-in Brotli support (e.g. Chrome), or to override the built-in deflate decompression for PNG files. The custom functions take a Uint8Array of compressed data and should return a Uint8Array or ArrayBuffer with the decompressed data (or a Promise that resolves to one).

Each function also receives a second argument, {maxOutputLength}: the most bytes it may produce for this block. That is one more than what is left of the maxDecompressedSize total for this load() call, so that a result cut off there still shows the block went over, and at most 1 GiB. The function has to stop there itself, since ExifReader can only check the result after the function returns. A function that stops by throwing an error whose code is 'ERR_BUFFER_TOO_LARGE', as Node's zlib does, counts as going over the total (see Limiting decompressed metadata size); any other error skips that block. Wrap a library function in an arrow function that passes on only what it understands instead of passing the library function itself, since its own second parameter may mean something else.

const tags = await ExifReader.load(file, {
    async: true,
    decompress: {
        brotli: async (compressedData, {maxOutputLength}) => myBrotliDecompress(compressedData, maxOutputLength),
    }
});

If a custom function is provided for a compression type, it takes priority over the built-in Compression Streams API. If not provided, the library falls back to the Compression Streams API when available.

In Node, zlib takes the limit directly:

import zlib from 'node:zlib';

const tags = await ExifReader.load(file, {
    async: true,
    decompress: {
        deflate: (data, {maxOutputLength}) => zlib.inflateSync(data, {maxOutputLength}),
        brotli: (data, {maxOutputLength}) => zlib.brotliDecompressSync(data, {maxOutputLength}),
    }
});

A lightweight browser-compatible Brotli decompression library is brotli-dec-wasm, though it is not widely used. A more popular alternative is brotli-wasm, but it's also larger:

import brotliPromise from 'brotli-wasm';
const brotli = await brotliPromise;

const tags = await ExifReader.load(file, {
    async: true,
    decompress: {
        brotli: async (data) => brotli.decompress(data),
    }
});

As written, this example does not pass maxOutputLength on, so a crafted file can make it allocate beyond the limit before ExifReader sees the result.

Limiting decompressed metadata size

To avoid excessive memory use from pathological compressed inputs, ExifReader caps the total decompressed size of the compressed metadata blocks in a file. The limit covers all blocks decompressed in one load() call together, not each block on its own. The default limit is 128 MiB, which is well above any realistic legitimate value. You can override it via the maxDecompressedSize field on the decompress option (in bytes):

const tags = await ExifReader.load(file, {
    async: true,
    decompress: {
        maxDecompressedSize: 16 * 1024 * 1024 // 16 MiB
    }
});

If a compressed block would take the total beyond the limit, that block and every later compressed block are skipped, one warning is logged via console.warn, and the rest of the tags are returned as usual. Blocks that are decompressed at the same time, such as several PNG text chunks, can all be skipped when together they go beyond the limit. The built-in Compression Streams paths stop at the limit. A custom brotli/deflate function receives its limit as maxOutputLength and has to stop there itself, because ExifReader can only check its result after it returns. With length: 'auto', each read attempt parses the bytes fetched so far and has its own total.

With async: true, ExifReader decompresses at most the first 255 compressed PNG text chunks (zTXt and compressed iTXt) of a file and skips later ones. Uncompressed text chunks are not limited.

Parsing XMP tags when not in a DOM environment

When using for example Node.js or a web worker, there is no native DOMParser available for parsing the XML used in XMP. In this case – and if XMP support is important to you – you can pass in a third-party parser to ExifReader. The parser needs to have a parseFromString method with the same API as the parseFromString from the DOMParser Web API.

Use xmldom 0.9.12 or later. ExifReader limits how deeply XMP elements can nest and how many markup nodes a packet can have, and it checks those limits the way xmldom reads markup. Older versions of xmldom read some markup differently, well-formed markup included, so with them a crafted file can get past the limits and make parsing slow.

linkedom also parses XMP correctly, but use it only for files you trust. ExifReader's limits do not hold with it: a crafted 1 MB file can block parsing for about a minute, and a larger one for longer. linkedom can also get stuck on some XML (see below). Other parsers may work if they follow the spec, with the same caveat.

Here is an example using xmldom:

import {DOMParser, onErrorStopParsing} from '@xmldom/xmldom';
// ...
const tags = ExifReader.load(fileBuffer, {domParser: new DOMParser({onError: onErrorStopParsing})});

The onError option is needed to avoid a seemingly infinite loop for some XMLs. Unfortunately linkedom has the same problem but does not have this option and will therefore get stuck on these XMLs. If this happens to you, switch to xmldom and pass in the onError option. (NOTE: The native DOMParser that a web browser uses does not seem to have this issue.)

ExifReader skips an XMP packet that has a DOCTYPE or another markup declaration, since a parser such as a browser's native DOMParser can expand the entities declared in a DOCTYPE into markup the limits do not see.

If you pass no domParser and there is no global DOMParser, ExifReader tries to load @xmldom/xmldom itself. It then skips XMP, with a warning, if the copy it finds is older than 0.9.12 or its version cannot be read. That copy can be the one at the top of your node_modules instead of ExifReader's own, for example when ExifReader is installed without optional dependencies, or when an npm override, a Yarn resolution or a pnpm override pins @xmldom/xmldom below 0.9.12. Install @xmldom/xmldom 0.9.12 or later, or pass a parser in the domParser option.

Using React Native

React Native 0.79 and later (Metro 0.82 and later) resolve the subpaths of the composable API, so you can import exifreader/core and the other subpaths directly and pass the same buffer as below to await reader.load(fileBuffer). React Native has no DOMParser, so a reader with xmp needs a parser passed to createReader in its domParser key (see Parsing XMP tags when not in a DOM environment).

Metro does not tree shake, so it loads every format and group the imported subpaths reference. Under Metro 0.88, a reader of JPEG files with gps and two tags is over 230 KiB raw and 60 KiB gzip. That is still smaller than the default entry under Metro (over 250 KiB and 75 KiB), but esbuild bundles the one-tag Single tags example of the composable API to about 39 KiB and 13 KiB.

With the default entry, or an older Metro, import ExifReader like this:

import ExifReader from './node_modules/exifreader/src/exif-reader.js';

Make sure to update the path to point to where your node_modules is located.

For local files on the device you need to load the file yourself first, then pass in the buffer to ExifReader. Here is a template from user @hungdev:

import RNFS from 'react-native-fs';
import {decode} from 'base64-arraybuffer';
import ExifReader from 'exifreader';

const b64Buffer = await RNFS.readFile('YOUR IMAGE URI', 'base64') // Where the URI looks like this: "file:///path/to/image/IMG_0123.HEIC"
const fileBuffer = decode(b64Buffer)
const tags = ExifReader.load(fileBuffer, {expanded: true});

If you're having trouble getting the GPS location, see this comment and thread and the GPS section below for more details.

GPS

If expanded: true is specified in the options, there will be a gps group. This group currently contains Latitude, Longitude, and Altitude which will be negative for values that are south of the equator, west of the IRM, or below sealevel. These are often more convenient values for regular use. For some elaboration or if you need the original values, see Notes below.

If you're having trouble getting the GPS values on Android (and possibly also IOS) and are using a type="file" input to upload the image, make sure you are not setting accept="image/*" on the input element. Apparently setting the accept attribute to this value will strip the GPS values.

Using the thumbnail

The thumbnail and its details will be accessible through tags['thumbnail']. There is information about e.g. width and height, and the thumbnail image data is stored in tags['thumbnail'].image.

How you use it is going to depend on your environment. For a web browser you can either use the raw byte data in tags['thumbnail'].image and use it the way you want, or you can use the helper property tags['thumbnail'].base64 that is a base64 representation of the image. It can be used for a data URI like this:

const tags = ExifReader.load(fileBuffer);
imageElement.src = 'data:image/jpg;base64,' + tags['thumbnail'].base64;

If you're using node, you can store it as a new file like this:

const fs = require('fs');
const tags = ExifReader.load(fileBuffer);
fs.writeFileSync('/path/to/new/thumbnail.jpg', Buffer.from(tags['thumbnail'].image));

On ExifReader.load and loadView, tags['Thumbnail'] is the old name of the same value and is removed in v5. Until then it is the one that Object.keys and JSON.stringify list, since thumbnail is not enumerable there, so a copy of the result (spread, Object.assign, structuredClone or a JSON round trip) keeps only Thumbnail. When a file has a PNG text or XMP tag named thumbnail, that tag keeps the key in the flat result, so code that has to handle such files reads Thumbnail until v5. A reader from the composable API returns only thumbnail.

See the examples site for more details.

Optimizing build size

Composable API

Import only the formats, groups and tags you read, and your bundler leaves out the rest.

Whole groups. This reader reads the Exif and XMP tags of JPEG and HEIC files:

import {createReader} from 'exifreader/core';
import {jpeg, heic} from 'exifreader/formats';
import {exif, xmp} from 'exifreader/groups';

const reader = createReader({formats: [jpeg, heic], groups: [exif, xmp]});
const tags = await reader.load(file);

Single tags. This one reads only the date and the GPS position of JPEG files:

import {createReader} from 'exifreader/core';
import {jpeg} from 'exifreader/formats';
import {gps} from 'exifreader/groups';
import {DateTimeOriginal} from 'exifreader/tags/exif';

const reader = createReader({formats: [jpeg], groups: [gps], tags: [DateTimeOriginal]});
const tags = await reader.load(file);
// tags.exif.DateTimeOriginal, tags.gps.Latitude, tags.gps.Longitude

The output is grouped, since a reader is built from groups. expanded: false gives flat output, for code that moves over from ExifReader.load (see Migrating to the composable API for what differs). In flat output the name thumbnail is reserved for the thumbnail, so a PNG text or XMP tag of that name is read from the grouped output (tags.png.thumbnail, tags.xmp.thumbnail). tags.gps (Latitude, Longitude and Altitude) is only in the grouped output. In a flat load, gps therefore adds no GPS values at all: a reader composed with gps alone returns only the file and jfif tags for a JPEG file. For GPS values in flat output, import GPSLatitude, GPSLatitudeRef, GPSLongitude, GPSLongitudeRef, GPSAltitude and GPSAltitudeRef from exifreader/tags/exif and pass them in tags. A flat load then has GPSLatitude with its unsigned decimal description, and the Ref tags carry the hemisphere and whether the altitude is below sea level (see Notes and the GPS section).

A group or tag the file does not hold is absent from the result, so tags.exif?.DateTimeOriginal?.description covers every case.

What a group brings. Each group reads the Exif tags it needs: gps the six GPS tags its values come from, xmp ApplicationNotes, iptc IPTC-NAA, icc ICC_Profile, photoshop ImageSourceData and PhotoshopSettings, makerNotes, canon and pentax MakerNote and Make, thumbnail JPEGInterchangeFormat and JPEGInterchangeFormatLength, and composite the focal length and pixel dimension tags it computes its values from. The reader reads those tags but returns them only when they are also in tags or the whole exif group is composed: with makerNotes, for example, add Make to tags to get exif.Make. A format brings its own tags: every format gives file (FileType, and the image details where the format has them), and jpeg adds jfif, png adds png, webp adds riff and gif adds gif. The grouped output of a composed reader has png alone, which holds every tag of pngFile and pngText, not those two groups.

Tags. tags takes Exif and IPTC tags, imported from exifreader/tags/exif and exifreader/tags/iptc. With iptc not in groups, a reader composed with IPTC tags returns only those, and it reads the block's Coded Character Set for the text encoding even when that tag is not in tags. MPF tags come only with the whole mpf group. Three IPTC tags come only with the whole iptc group: ObjectData Preview File Format and Record 2 destination (dataset 2:200), whose name depends on the length of the value, so no import can select it, and ObjectData Preview File Format Version (2:201), whose description is read from dataset 2:200. A tag's import name differs from its key in the result when its name has characters a JavaScript name cannot hold, so ByLine is read as tags.iptc['By-line'] and SubLocation as tags.iptc['Sub-location']. The keys in the result are the same as in ExifReader.load. On a composed reader, a repeatable IPTC dataset such as Keywords is always an array of tag objects, also when the file holds it once. In the flat output an XMP tag of the same name replaces it, as it does in ExifReader.load.

Subpaths.

Subpath Exports
exifreader/core createReader, errors (UnsupportedFormatError), tagFilter
exifreader/formats tiff, jpeg, png, heic, avif, jxl, webp, gif, xml (XMP sidecar files; returns only FileType without xmp in groups), allFormats
exifreader/groups exif, iptc, xmp, icc, photoshop, mpf, makerNotes, canon, pentax, gps, composite, thumbnail, allGroups
exifreader/tags/exif, exifreader/tags/iptc One export per tag, named after the tag with every character that cannot be in a JavaScript name removed and the letter after it upper-cased (By-line becomes ByLine, GPS Info IFD Pointer becomes GPSInfoIFDPointer)

makerNotes holds every maker note decoder and grows with new releases. canon and pentax hold one each.

Pass these values as they are imported. A copy or an altered copy of a format, group or tag is not supported.

Everything. createReader({formats: allFormats, groups: allGroups}) reads everything (allGroups has makerNotes, not canon or pentax). Filtering these arrays skips parsing but does not shrink the bundle, since the bundler cannot see which entries you keep. Import by name instead. Composing heic without avif saves little (under 0.1 KiB).

Loading. reader.load takes the image bytes or a Blob or File:

You have Call
A File from <input type="file"> reader.load(file); for the first n bytes, reader.load(file.slice(0, n))
A path in Node reader.load(await readFile(path)) (readFile from node:fs/promises)
A path in Node, the first n bytes only reader.load((await openAsBlob(path)).slice(0, n)) (openAsBlob from node:fs)
A path in Bun reader.load(Bun.file(path))
A URL reader.load(await (await fetch(url)).arrayBuffer())
A Response reader.load(await response.arrayBuffer())
A ReadableStream reader.load(await new Response(stream).arrayBuffer())
Bytes: an ArrayBuffer, SharedArrayBuffer, DataView, typed array such as Uint8Array, or Node Buffer reader.load(bytes)

reader.load always returns a Promise and never throws: every failure is a rejection. It does not take strings or URLs, and it has no length or async option (both reject). Passing domParser or decompress to reader.load rejects too, as both go to createReader. The options it takes are expanded, includeUnknown, computed, includeOffsets, includeTags and excludeTags; the first four take only true, false or undefined, and any other value rejects. expanded: false gives the flat output, and includeOffsets needs no expanded (it does nothing with expanded: false).

Errors. Input that no composed format recognizes rejects with UnsupportedFormatError, so a reader of JPEG files only rejects a PNG file that way. The message names the formats of the reader in detection order: the JPEG-only reader below rejects with reader.load: none of this reader's formats (jpeg) recognizes the input: it is in another format or is not an image. Check for it with error instanceof errors.UnsupportedFormatError, using the errors of the entry the reader came from (exifreader/core for createReader, ExifReader.errors for the default entry, which under Node is the bundled dist file with its own copy of the class), or with error.name === 'UnsupportedFormatError':

import {createReader, errors} from 'exifreader/core';
import {jpeg} from 'exifreader/formats';
import {exif} from 'exifreader/groups';

const reader = createReader({formats: [jpeg], groups: [exif]});
try {
    const tags = await reader.load(file);
} catch (error) {
    if (error instanceof errors.UnsupportedFormatError) {
        // Not a JPEG file.
    }
}

XMP outside browsers. Node, Bun, Deno, web workers and React Native have no DOMParser. With xmp composed, pass one to createReader in its domParser key (see Parsing XMP tags when not in a DOM environment):

import {createReader} from 'exifreader/core';
import {jpeg} from 'exifreader/formats';
import {xmp} from 'exifreader/groups';
import {DOMParser, onErrorStopParsing} from '@xmldom/xmldom';

const reader = createReader({formats: [jpeg], groups: [xmp], domParser: new DOMParser({onError: onErrorStopParsing})});
const tags = await reader.load(data);

Without one, reader.load rejects with a message naming domParser. The check runs at load, so creating the reader where there is no DOMParser, such as during server rendering, does not throw. A composed reader never loads @xmldom/xmldom by itself.

Decompression. Custom Brotli or deflate functions and maxDecompressedSize go to createReader in its decompress key, the object that Custom decompression and Limiting decompressed metadata size describe for ExifReader.load. The limit applies to each reader.load call on its own:

import zlib from 'node:zlib';
import {createReader} from 'exifreader/core';
import {jxl} from 'exifreader/formats';
import {exif} from 'exifreader/groups';

const reader = createReader({
    formats: [jxl],
    groups: [exif],
    decompress: {
        brotli: (data, {maxOutputLength}) => zlib.brotliDecompressSync(data, {maxOutputLength}),
        maxDecompressedSize: 16 * 1024 * 1024
    }
});

Filtering. includeTags and excludeTags need tagFilter, imported from exifreader/core, in createReader. Without it, reader.load rejects with a message naming the option. With it, reader.load also rejects an option that is not an object keyed by group, a key that is not a group (a misspelt one such as exiff), and a group value other than true, false or an array of tag names or ids. A group the reader does not compose is not an error: it is absent from the result. The options narrow what the reader composes and never add to it. See Filtering tags for their shapes.

import {createReader, tagFilter} from 'exifreader/core';
import {jpeg} from 'exifreader/formats';
import {exif, mpf} from 'exifreader/groups';

const reader = createReader({formats: [jpeg], groups: [exif, mpf], tagFilter});
const tags = await reader.load(file, {excludeTags: {mpf: true}});

Types. In TypeScript, the grouped result of reader.load has only the groups and tags the reader composes, so tags.gps does not compile on a reader without gps. Each group has only its own tag names, so tags.exif?.Headline, an IPTC name, does not compile either. includeTags and excludeTags compile only on a reader created with tagFilter (type options built before the call as LoadOptions<false> for a reader without it). A table whose contents TypeScript cannot see, such as allFormats, allGroups or an array typed Format[] or Group[], gives every group instead, typed as the ExpandedTags of exifreader/core. The flat output is typed Tags on every reader.

Runtime. The subpaths are published as source, not transpiled. The code is ES2015, and the composite group also uses the ES2016 ** operator. A reader uses these platform APIs when it needs them: Promise for every load; TextDecoder for text in IPTC, XMP and decompressed data and for the Windows XP tags; DecompressionStream for compressed metadata in PNG and JPEG XL files, unless decompress gives the functions; DOMParser for xmp, unless domParser is given; btoa for the base64 of a thumbnail or an MPF image; and Blob only when one is passed to reader.load.

Toolchains. The subpaths are ES modules only, resolved through the package's exports map. They work with webpack 5, Vite, Rollup with @rollup/plugin-node-resolve, esbuild, Parcel 2 with packageExports enabled, Bun, Deno, Metro 0.82 (React Native 0.79), TypeScript with moduleResolution set to bundler, node16 or nodenext, and Node with import (require() needs Node 20.19 or later on Node 20, or 22.12 or later). Some toolchains need extra setup or have limits:

  • TypeScript. A CommonJS importer (a .cts file, or a .ts file in a package without "type": "module") gets TS1479 on the subpath imports with module set to node16 or node18. It needs module set to nodenext (TypeScript 5.8 or later) or node20 (TypeScript 5.9 or later). An ES module importer works with all of them.
  • Jest. Jest 28 to 30 fail with their default configuration, since Jest does not transform node_modules. They work with a Babel transform plus transformIgnorePatterns: ['/node_modules/(?!exifreader/)'], or with --experimental-vm-modules when the test files are ES modules themselves.
  • eslint-plugin-import. With its default resolver it reports import/no-unresolved on the subpaths, since that resolver does not read exports.
  • Parcel. Parcel 2.16.4 resolves the subpaths with packageExports enabled but leaves unreferenced code in the bundle: the Single tags example is about 20 KiB gzip there against 13 KiB with esbuild.
  • CommonJS-compiled consumers. A consumer compiled to CommonJS before bundling (require('exifreader/core')) loses tree shaking under esbuild and Vite 8 (a JPEG reader with DateTimeOriginal: over 120 KiB raw against 37 KiB). webpack 5, Rspack and bun build keep it.
  • No tree shaking. Without a tree-shaking bundler (Metro, unbundled Node, Deno or Bun), every format and group the imported subpaths reference is loaded.

Migrating to the composable API

A reader from createReader reads the same tags as ExifReader.load and describes them the same way. What differs when you move over from ExifReader.load or from a custom build:

ExifReader.load A reader from createReader
Output Flat by default, grouped with expanded: true Grouped by default, flat with expanded: false
Return value The tags, or a Promise when it loads the file or with async: true Always a Promise
Input Bytes, a File, a path or a URL Bytes, a Blob or a File (see Loading for a path or a URL)
Part of a file The length option Slice it first: reader.load(file.slice(0, n))
domParser and decompress Options of load Passed to createReader
XMP outside browsers Looks for @xmldom/xmldom when no domParser is given Needs domParser; nothing is looked up
includeTags and excludeTags Always available Need tagFilter from exifreader/core in createReader
Options An unknown option is ignored, and any truthy value turns an option on An unknown option rejects, and so does a value other than true, false or undefined
PNG groups png, pngFile and pngText png
A repeatable IPTC dataset such as Keywords A tag when the file holds it once, an array when it holds several Always an array
A group with no tags {} Absent
Thumbnail tags.thumbnail, and tags.Thumbnail until v5 tags.thumbnail
base64 of the thumbnail and MPF images From Buffer or btoa From btoa; undefined where there is none
Errors ExifReader.errors errors from exifreader/core
Published code A UMD dist file, transpiled to ES5 ES modules, not transpiled (see Runtime)
Custom build The exifreader key in package.json and npx exifreader build Imports; npx exifreader analyze --imports <images> prints them

Default entry

The custom build was the previous way to a smaller bundle. It still works in v4, but it is deprecated and will be removed in v5, so use the composable API above instead.

If you use the default entry (import ExifReader from 'exifreader') with Webpack 4 or lower and are only targeting web browsers, make sure to add this to your Webpack config (probably the webpack.config.js file):

    node: {
        Buffer: false
    }

Buffer is only used in Node.js but if Webpack sees a reference to it it will include a Buffer shim for browsers. This configuration will stop Webpack from doing that. Webpack 5 does this automatically.

Configure a Custom Build

Configuring a custom build can reduce the bundle size significantly.

NOTE 1: The custom build was the previous way to a small bundle. It is still supported in v4, but it is deprecated and will be removed in v5. The composable API replaces it.

NOTE 2: This only changes the built file (exifreader/dist/exif-reader.js), not the source code. That means it's not possible to use the ES module (from the src folder) or any tree shaking to get the benefit of a custom build. Tree shaking has close to no effect on a custom build, so don't rely on it.

Which file a plain import ExifReader from 'exifreader' or require('exifreader') resolves to depends on the tool:

  • dist/exif-reader.js, which picks up a custom build: Node, Bun, Deno, React Native's Metro (native platforms), webpack with target: 'node' and esbuild with platform: 'node'.
  • src/exif-reader.js, which never picks up a custom build: webpack 5, Vite, Parcel 2 and Metro when they build for the web, Rollup with @rollup/plugin-node-resolve and esbuild with platform: 'browser'.

If you bundle for the browser and use a custom build, import the built file directly: import ExifReader from 'exifreader/dist/exif-reader';.

This is for npm and yarn users that use the built file. To specify what functionality you want you can either use include pattern (start with an empty set and include) or exclude pattern (start with full functionality and exclude). If an include pattern is set, excludes will not be used.

For Exif and IPTC it's also possible to specify which tags you're interested in. Those tag groups have huge dictionaries of tags and you may not be interested in all of them. (Note that it's not possible to specify tags to exclude.)

The configuration is added to your project's package.json file.

Example 1: Only include JPEG files and Exif tags (this makes the bundle almost half the size of the full one (non-gzipped)):

"exifreader": {
    "include": {
        "jpeg": true,
        "exif": true
    }
}

Example 2: Only include TIFF files, and the Exif DateTime tag and the GPS tags (resulting bundle will be about a third of a gzipped full build):

"exifreader": {
    "include": {
        "tiff": true,
        "exif": [
            "DateTime",
            "GPSLatitude",
            "GPSLatitudeRef",
            "GPSLongitude",
            "GPSLongitudeRef",
            "GPSAltitude",
            "GPSAltitudeRef"
        ]
    }
}

Example 3: Exclude XMP tags:

"exifreader": {
    "exclude": {
        "xmp": true
    }
}

Then build the custom bundle. If you haven't installed ExifReader yet:

npm install exifreader
npx exifreader build

If it is already installed, or you just changed the configuration, run:

npx exifreader build

This reads the exifreader configuration from your package.json, rebuilds the library, and writes the result to node_modules/exifreader/dist/exif-reader.js. It works the same way with npm, yarn, and pnpm.

Derive the configuration from your images. Instead of writing the configuration by hand, point analyze at a directory of sample images (or at individual files):

npx exifreader analyze ./samples

It reads the images with the full library and prints the smallest include configuration that reads everything found in them: the file formats, the Exif and IPTC tags, and the XMP, ICC, Photoshop, maker note, MPF and thumbnail groups. Add --write to put it in your package.json, replacing any include or exclude section there, then run npx exifreader build. Add --imports instead to print the equivalent createReader imports of the composable API in place of the configuration. To analyze and build in one step, and then check the result:

npx exifreader build --auto ./samples --verify

--verify (which also works without --auto) reads the images with both the full library and the installed custom bundle and exits with an error listing every difference.

The configuration covers exactly what the sample images contain, so use a sample that is representative of the images your app reads. A format, tag or group that is not in the samples is left out of the build. Pass every sample in one run, since each run replaces the configuration instead of adding to it. build --auto does not save the configuration. A later npm ci restores the full bundle, and a plain build, build --check or build --if-needed reads the configuration in package.json instead. For a lasting setup, run analyze --write once and then build (or build --if-needed in a script). Use build --auto for one-off builds.

Re-run after every install. A fresh npm install, npm ci, or upgrade restores the full bundle, so run npx exifreader build again afterwards. The most reliable approach is to wire it into your own build step, for example (in your own package.json):

"scripts": {
    "prebuild": "exifreader build --if-needed"
}

With --if-needed the rebuild is skipped when the installed bundle was already built from the current configuration and exifreader version. Each custom build records these in node_modules/exifreader/dist/.exifreader-custom-build.json.

To catch a stock or outdated bundle in CI, add a step that runs:

npx exifreader build --check

It never builds anything. It exits with a non-zero code when the installed bundle is the stock full build or was built from a different configuration or exifreader version, and with 0 when it is up to date or when no configuration is found. --check and --if-needed only see the configuration source they are given, so pass them the same one as the build: a project that builds with --config exifreader.json checks with npx exifreader build --check --config exifreader.json, since without it no configuration is found and --check exits with 0.

Deprecated: automatic rebuild on install. Older versions rebuilt the library automatically through an npm postinstall script, so a plain install or npm rebuild exifreader (or yarn add exifreader with yarn 1) produced the custom bundle. This still works in v4 but is deprecated and will be removed in v5, because npm is phasing out automatic install scripts. Yarn 4.14 and later disable dependency build scripts by default (an install prints YN0004 ... all build scripts have been disabled), so there the install-time build only runs if you enable build scripts, with Yarn's enableScripts setting or the built flag in dependenciesMeta. Use npx exifreader build (or yarn exifreader build with Yarn) instead, which does not depend on build scripts. With Yarn 2+ it needs a node_modules install (nodeLinker: node-modules in .yarnrc.yml), not Plug'n'Play.

If you are using vite, you will need to clear the dependency cache after a rebuild.

Advanced and monorepos. Instead of the package.json configuration you can put the same include/exclude object in a JSON file and pass it with npx exifreader build --config <path> (a relative path is resolved from the current directory), or pass it as JSON in the EXIFREADER_CUSTOM_BUILD environment variable. --config takes priority over EXIFREADER_CUSTOM_BUILD, which takes priority over package.json. In a monorepo, npx exifreader build reads the configuration from the package you run it in, but a hoisted node_modules/exifreader (or, with pnpm, the copy in the workspace root's node_modules/.pnpm) is shared by every workspace package, so there is only one custom bundle and the last build wins. The CLI prints a warning when you build from a workspace package into such a shared copy.

If you're using the include pattern config, remember to include everything you want to use. If you want xmp and don't specify any file types, you will get "Invalid image format", and if you specify jpeg but don't mention any tag types no tags will be found.

Possible modules to include or exclude:

Module Description
jpeg JPEG images.
tiff TIFF images.
png PNG images.
heic HEIC/HEIF images.
avif AVIF images.
webp WebP images.
jxl JPEG XL images.
gif GIF images.
file JPEG file details: image width, height etc. The image details of JPEG XL, HEIC/HEIF and AVIF files come with their format module.
jfif JFIF details in JPEG files: resolution, thumbnail etc.
png_file PNG file details: image width, height etc.
exif Regular Exif tags. If excluded, will also exclude photoshop, maker_notes, and thumbnail. Also excludes the IPTC, XMP and ICC tags that are read from the Exif data, which in TIFF files is all of them.
iptc IPTC tags.
xmp XMP tags.
icc ICC color profile tags.
mpf Multi-picture Format tags. Does not need exif.
photoshop Photoshop tags. Needs exif.
maker_notes Proprietary camera maker tags. Needs exif.
thumbnail Thumbnail image. Needs exif.

Notes

  • In Exif data, the full GPS information is split into two different tags for each direction: the coordinate value (GPSLatitude, GPSLongitude) and the reference value (GPSLatitudeRef, GPSLongitudeRef). Use the references to know whether the coordinate is north/south and east/west. The description of GPSLatitude, GPSLongitude, GPSDestLatitude and GPSDestLongitude is the decimal coordinate as a number, unsigned, with the reference tag giving the hemisphere. It is NaN when the value holds fewer than three [numerator, denominator] pairs. Often you will see north and east represented as positive values, and south and west represented as negative values (e.g. in Google Maps). This setup is also used for the altitude using GPSAltitude and GPSAltitudeRef where the latter specifies if it's above sea level (positive) or below sea level (negative). If you don't want to calculate the final values yourself, see the section on GPS for pre-calculated ones.
  • Some XMP tags have processed values as descriptions. That means that e.g. an Orientation value of 3 will have Rotate 180 in the description property. If you would like more XMP tags to have a processed description, please file an issue or create a pull request.
  • Some text tags use TextDecoder to decode their content. If your specific environment does not support it at all or a specific encoding, you will not be able to see the decoded value. One example is when Node.js wasn't compiled with support for the specific encoding.
  • The description property of tags can change in a minor update. If you want to process a tag's value somehow, use the value property to be sure nothing breaks between updates.
  • Some of the composite tags may have values that are very off if e.g. the image has been resized.

Client/Browser Support

The library makes use of the DataView API which is supported in Chrome 9+, Firefox 15+, Internet Explorer 10+, Edge, Safari 5.1+, Opera 12.1+. For Node.js at least version 10 is required if you want to parse XMP tags, otherwise earlier versions will also work.

Examples

Full HTML example pages and a Node.js example are located on the examples site.

Tips

  • After parsing the tags, consider deleting the MakerNote tag if you know you will load a lot of files and storing the tags. It can be really large for some manufacturers. See the examples site to see how you can do that. On a reader from the composable API, leaving makerNotes out of groups skips decoding the maker notes, but a whole exif group still returns the raw MakerNote tag. Compose the Exif tags you need by name instead, or drop it with excludeTags: {exif: ['MakerNote']} on a reader composed with tagFilter.
  • In some cases it can make sense to only load the beginning of the image file since that is where the metadata is located. It's unfortunately not possible to know how big the metadata will be in an image, but if you limit yourself to regular Exif tags you can most probably get by with only reading the first 128 kB. This may exclude IPTC and XMP metadata though (and possibly Exif too if they come in an irregular order) so please check if this optimization fits your use case. Use the length option to only read the beginning of the file. See above for more details on that.
  • Excluding MPF (Multi-Picture Format) makes a big difference for phone photos. Modern phone JPEGs embed a sub-image preview a few MB into the file. If you do not need it, pass excludeTags: {mpf: true}. This is especially impactful when combined with length: 'auto' (multi-x speedup, see that section), but it also lets a numeric length boundary land well before the sub-image. Regular Exif/XMP/ICC tags are unaffected. On a reader from the composable API, leave mpf out of groups, or pass excludeTags: {mpf: true} to a reader composed with mpf and tagFilter.

Known Limitations

  • The descriptions for UserComment, GPSProcessingMethod and GPSAreaInformation are missing for other encodings than ASCII.
  • For Canon maker notes, makerNotes.LensType is currently returned as a raw numeric code (for example 48). If you need a human-readable lens name, see ExifTool's Canon LensType mapping list: https://exiftool.org/TagNames/Canon.html#LensType.

Contributing

Questions, bug reports, suggestions, and pull requests are very much welcome. If you've been using another Exif package, you probably have some good insights on what's missing in this one. See CONTRIBUTING.md for more info.

Code of Conduct

This project is released with a Contributor Code of Conduct. By participating in this project you agree to abide by its terms.

License

ExifReader uses the Mozilla Public License 2.0 (MPL-2.0). In short that means you can use this library in your project (open- or closed-source) as long as you mention the use of ExifReader and make any changes to ExifReader code available if you would to distribute your project. But please read the full license text to make sure your specific case is covered.

About

A JavaScript Exif info parser.

Resources

Code of conduct

Contributing

Security policy

Stars

1.0k stars

Watchers

12 watching

Forks

Releases

Sponsor this project

Packages

Used by

Contributors

Languages