How a JPEG file is built
JPEG (ITU-T T.81, ISO/IEC 10918-1) compresses photographs with loss: the image is cut into 8×8
blocks, each block is turned into frequencies (the discrete cosine transform, DCT), the frequencies are
divided by a quantization table and rounded (this is where detail is lost), and the result is
compressed with Huffman codes. Around the compressed data, the file is a sequence of markers;
the “JPEG file” most software writes is the JFIF or Exif layout of those markers. This page describes them
as the JPEG tool reads them, the metadata phones and editors add, and the JpegFile library.
- Android:
res/drawable*/ and assets/ in an APK hold JPEGs as the
developer exported them (aapt doesn't recompress them), so their metadata survives into the app.
- iOS: JPEGs copied into an app bundle keep their metadata too; photos an app takes or picks from
the library carry Exif, often with a GPS position, until the app strips it.
Contents
- Markers and segments
- The order of a file
- The frame header: size, components, subsampling
- Quantization tables and the quality
- Huffman tables
- Scans and the entropy-coded data
- Baseline, progressive and the other processes
- APP segments: JFIF, Exif, XMP, ICC, MPF, Adobe, Photoshop
- What to look for
- What the tool shows, and its limits
- The JpegFile library
- The Exif library
1Markers and segments
A marker is a FF byte followed by a code. Any number of extra FF fill bytes may
come before the code. Four kinds of marker stand alone; every other one starts a segment: a 2-byte
big-endian length that counts itself but not the marker, then the data. A segment therefore holds at most
65,533 bytes of data, which is why large metadata (ICC profiles, extended XMP) is split over several
segments.
| Code |
Name |
What it is |
| D8 |
SOI |
Start of image: the first two bytes of every JPEG (FF D8). Stands alone. |
| E0–EF |
APP0–APP15 |
Application data, identified by a signature at the start of the data (JFIF\0,
Exif\0\0…). |
| DB |
DQT |
Define quantization tables. |
| C4 |
DHT |
Define Huffman tables. |
| CC |
DAC |
Define arithmetic-coding conditioning (instead of DHT, for arithmetic coding). |
| C0–CF |
SOF0–SOF15 |
Start of frame: the image's size and components, and the coding process (but C4, C8 and CC,
which are DHT, JPG and DAC). |
| DD |
DRI |
Define restart interval: a restart marker every so many MCUs. |
| DA |
SOS |
Start of scan; the entropy-coded data follows the segment. |
| D0–D7 |
RST0–RST7 |
Restart markers inside the entropy-coded data, counting 0 to 7 and around. Stand alone. |
| FE |
COM |
A comment: text, in no defined encoding. |
| DC · DE · DF |
DNL · DHP · EXP |
Number of lines (when the frame's height was 0), and the hierarchical process's progression and
expansion. |
| F0–FD |
JPG0–JPG13 |
Reserved for extensions; JPEG-LS uses F7 (SOF55) and F8 (LSE). |
| 01 |
TEM |
Temporary, for arithmetic coding. Stands alone. |
| D9 |
EOI |
End of image. Stands alone. Bytes after it are not part of the image. |
Codes 02–BF are reserved: a file that has them is damaged, or isn't really a JPEG at that point.
2The order of a file
A typical photo from a phone:
FF D8 SOI
FF E1 … "Exif\0\0" APP1: Exif (camera, dates, GPS, a thumbnail)
FF E1 … "http://ns.adobe.com/xap/1.0/\0" APP1: XMP
FF E2 … "ICC_PROFILE\0" APP2: the colour profile (Display P3 on iPhones)
FF E2 … "MPF\0" APP2: the index of the other images (iPhone gain maps, depth)
FF DB … DQT: quantization tables
FF C0 … SOF0: 4032 × 3024, Y Cb Cr, 4:2:0
FF C4 … DHT: Huffman tables
FF DD … DRI (optional)
FF DA … SOS, then the entropy-coded data
FF D9 EOI
… the other MPF images, or appended data
JFIF requires its APP0 right after SOI and Exif requires its APP1 there; in practice both appear, in either
order, and readers accept either. The tables can be anywhere before the scan that uses them, and can be
redefined between scans.
3The frame header: size, components, subsampling
| Bytes |
Field |
Meaning |
| 1 |
P |
Sample precision: 8 bits (baseline), 8 or 12 (extended, progressive), 2–16 (lossless). |
| 2 + 2 |
Y, X |
Height and width in pixels. A height of 0 means a DNL marker gives it after the first scan. |
| 1 |
Nf |
The number of components: 1 (greyscale), 3 (Y Cb Cr, or RGB), 4 (CMYK or YCCK). |
| 3 × Nf |
C, H×V, Tq |
For each component: an id, its horizontal and vertical sampling factors (1–4, a nibble each),
and the quantization table it uses. |
Components. JFIF numbers them 1, 2, 3 for Y, Cb, Cr. Ids 'R' 'G' 'B', or an Adobe APP14
segment with transform 0, mean the components are RGB, without colour conversion. With four components,
Adobe's transform 2 means YCCK, otherwise CMYK; Photoshop writes CMYK inverted (0 is full ink).
Chroma subsampling. The eye sees less colour detail than brightness, so encoders store Cb and Cr at a
lower resolution. The sampling factors say how many blocks of each component make up one MCU (minimum
coded unit), relative to the largest:
| Y |
Cb, Cr |
Name |
Colour resolution |
| 1×1 |
1×1 |
4:4:4 |
full (quality settings above about 90, and Photoshop's high qualities) |
| 2×1 |
1×1 |
4:2:2 |
half horizontally (cameras, video) |
| 2×2 |
1×1 |
4:2:0 |
half in each direction (most phones and the libjpeg default) |
| 1×2 |
1×1 |
4:4:0 |
half vertically |
| 4×1 |
1×1 |
4:1:1 |
a quarter horizontally (DV video) |
A 4:2:0 MCU is 16×16 pixels: four Y blocks, one Cb and one Cr. Images whose size isn't a multiple of the MCU
are padded on the right and bottom; the padding is encoded but not shown.
4Quantization tables and the quality
A DQT segment holds one or more tables: a byte with the precision (high nibble: 0 = 8-bit values, 1 = 16-bit)
and the id (0–3), then 64 values in zigzag order: from the top-left (DC, the block's average) along
anti-diagonals to the bottom-right (the highest frequencies). Each coefficient is divided by its value;
large values at the high frequencies are what makes JPEG small.
The quality setting isn't stored. libjpeg (IJG), which most encoders and image libraries use, makes
its tables by scaling the example tables of the standard (Annex K, one for luminance and one for
chrominance): for a quality q, the scale is 5000 / q percent below 50 and 200 − 2q
percent from 50, each value becomes (example × scale + 50) / 100, at least 1, at most 255. The tool
compares each table with these for every quality from 1 to 100 and reports the closest. An exact
match tells that the image came out of libjpeg (or a library built on it) at that quality; a close but
inexact one, that the encoder used its own tables (Photoshop, Apple, Samsung and most cameras do), and the
number is only an indication. Quality 100 gives tables of all 1s.
The tables also fingerprint the encoder: the same camera model or app always writes the same ones, which
forensic tools use to tell whether a photo was re-saved by another program.
5Huffman tables
A DHT segment holds one or more tables: a byte with the class (high nibble: 0 = DC, 1 = AC) and the id (0–3),
16 counts (how many codes have each length from 1 to 16 bits), then the symbols in order of code length. The
codes themselves aren't stored: they are canonical, assigned in order (0, 10, 110…), so the counts and
symbols are enough.
- A DC symbol is the number of bits of the difference from the previous block's DC value (0–11),
which follow the code.
- An AC symbol is two nibbles: how many zero coefficients come first (the run, 0–15) and the size
of the next non-zero one;
00 is end-of-block, F0 a run of 16 zeros.
The standard offers example tables (Annex K.3) that work for typical photos; encoders that don't optimize use
them (the tool says “standard”). An optimized table is built from the image's own statistics, saving a few
percent. Motion-JPEG frames from cameras and AVI files often leave the DHT out entirely and expect the
decoder to use the standard tables.
6Scans and the entropy-coded data
An SOS segment lists the components of the scan, the DC and AC Huffman tables of each, and three numbers used
by progressive images: the first and last coefficient of the scan (Ss–Se, the spectral selection) and
the successive approximation bits (Ah/Al: the bit position of the previous pass and of this one).
The entropy-coded data follows immediately, without a length: a reader finds its end by looking for
the next marker. Inside it:
- Byte stuffing: a data byte
FF is followed by 00, so it isn't taken for
a marker.
- Restart markers RST0–RST7 come every n MCUs when a DRI segment set an interval n.
They reset the DC prediction so a damaged stretch doesn't spoil the rest, and let decoders work on parts
in parallel. The tool counts them and compares with the number the interval implies.
A file cut short (a partial download, a carved file) ends inside this data, without EOI; most decoders show
the top of the image and grey or garbage below.
7Baseline, progressive and the other processes
| Marker |
Process |
| SOF0 |
Baseline: sequential DCT, 8-bit samples, Huffman coding, at most two tables of each kind.
Every decoder supports it. |
| SOF1 |
Extended sequential: 8 or 12 bits, four tables of each kind. |
| SOF2 |
Progressive: the image arrives in several scans, from coarse to fine. |
| SOF3 |
Lossless: prediction from neighbouring pixels instead of the DCT (rare; some medical images).
|
| SOF5–7 |
Hierarchical (differential) versions of the above: several resolutions in one file. Almost never
used. |
| SOF9–15 |
The same processes with arithmetic coding instead of Huffman: about 5–10% smaller, long
patented, and unsupported by browsers. |
A sequential image has one scan (or one per component when they aren't interleaved): each block is
coded completely, top to bottom. A progressive image codes all blocks several times: a first scan
with the DC coefficients of all components (a blurry image, often with the low bit held back, Al =
1), then scans of AC bands of one component at a time (for example coefficients 1–5, then 6–63), then
refinement scans (Ah > 0) that add the bits held back. Browsers draw the image after each
scan. libjpeg's default progressive script has 10 scans; Photoshop's “Save for Web” writes more. Progressive
files have their own Huffman tables, often redefined between scans.
8APP segments: JFIF, Exif, XMP, ICC, MPF, Adobe, Photoshop
| Segment |
Signature |
Contents |
| APP0 |
JFIF\0 |
The JFIF version, the pixel density (dpi, dots per cm, or only an aspect ratio) and an optional
tiny uncompressed RGB thumbnail. JFXX\0 extends it with a JPEG thumbnail.
AVI1 marks a Motion-JPEG frame. |
| APP1 |
Exif\0\0 |
Exif: a TIFF structure (byte order II or MM, then directories of
tags). IFD0 describes the image (Make, Model, Software, DateTime, Orientation); the Exif
directory the shot (exposure, ISO, lens, the original date, the pixel size); the GPS directory
the position, altitude, direction and time; IFD1 a JPEG thumbnail, usually 160×120. Offsets
count from the TIFF header, 6 bytes into the segment. |
| APP1 |
http://ns.adobe.com/xap/1.0/\0 |
XMP: RDF/XML metadata (editing history, the creator tool, ratings, Apple's and Google's camera
data, HDR gain map parameters). When it doesn't fit, the rest is extended XMP
(http://ns.adobe.com/xmp/extension/\0): pieces with the MD5 of the whole as a
32-character GUID, its total length and the piece's offset; the main packet names the GUID in
xmpNote:HasExtendedXMP. |
| APP2 |
ICC_PROFILE\0 |
The colour profile, in numbered pieces (a 1-based sequence number and the total count, then up
to 65,519 bytes). The profile's header gives its version, device class and colour space; its
desc tag a name such as “Display P3”. |
| APP2 |
MPF\0 |
Multi-Picture Format (CIPA DC-007): a TIFF structure whose MP Entry lists every image of the
file (type, size, offset from the MPF's TIFF header; the first image has offset 0). Stereo
cameras (MPO files) store their second view this way; iPhones store the HDR gain map and other
auxiliary images after the main image's EOI, with their own XMP describing them. |
| APP2 |
urn:iso:std:iso:ts:21496:-1\0 |
ISO 21496-1 gain map metadata (the Ultra HDR / Adobe gain map standard). |
| APP11 |
JP |
JUMBF boxes, used by C2PA “content credentials” (signed provenance). |
| APP12 |
Ducky |
Written by Photoshop's “Save for Web”: the quality setting (0–100), and optionally a comment and
a copyright. |
| APP13 |
Photoshop 3.0\0 |
Photoshop image resources (8BIM blocks: an id, a name, a size): resolution, a
thumbnail, print settings, slices, and the IPTC-NAA record (resource 0x0404) with press
metadata: caption, keywords, by-line, city, copyright. |
| APP14 |
Adobe |
A version, two flag words, and the colour transform: 0 none (RGB or CMYK), 1 YCbCr, 2 YCCK. |
Unknown APP segments are skipped by decoders. The tool shows their signature (the readable text at the
start) when it has one.
9What to look for
- GPS position in Exif: where the photo was taken, to a few metres. A photo bundled in an app can
locate its developer's office or home; an app that uploads users' photos without stripping Exif
publishes where they live. Also
GPSTimeStamp, GPSImgDirection and the
altitude.
- Device and owner:
Make, Model, BodySerialNumber,
LensSerialNumber, CameraOwnerName, Artist,
Copyright, Apple's MakerNote, and the IPTC by-line.
- Software: the
Software tag, XMP's CreatorTool and history (often with
file paths and user names from the designer's machine), Photoshop resources, the Ducky segment.
- Thumbnails that weren't updated: many editors change the image but keep the camera's Exif
thumbnail, which may still show what was cropped out or retouched. The tool warns when the thumbnail's
shape, or the Exif pixel size, doesn't match the image; open the thumbnail in its own tab to look at it.
- Appended data after EOI: archives, scripts or keys hidden in an image, which every viewer
ignores. Some of it is legitimate: MPF images (gain maps, depth), Google's motion photos (an MP4 video
after the image, described in XMP), Samsung's trailer (
SEFT at the very end). The tool
marks what the MPF index explains.
- Second JPEGs: a full image inside the Exif thumbnail, the Photoshop thumbnail or after EOI can
differ from what is displayed.
- Damage: a truncated scan, unknown markers, restart markers out of sequence, or tables used but
not defined.
10What the tool shows, and its limits
The overview (process, subsampling, quality estimate, metadata, problems, and a bar of how the file's bytes
are used), every marker segment and block of entropy-coded data with its fields decoded and its bytes, the
metadata (Exif with the GPS position, XMP indented, the ICC profile's header, comments, Photoshop resources
and IPTC, JFIF, Adobe, Ducky, MPF), the frame and its scans, the quantization tables as 8×8 grids and the
Huffman tables with their codes, and the embedded images, each of which opens in a new JPEG tool tab.
It doesn't decode or draw the image: it doesn't run the Huffman decoding, so it can't tell whether the
entropy-coded data is valid inside, only where it ends, how many restart markers and stuffed bytes it holds,
and whether it is cut short. It reads only the header of an ICC profile and its description, not its curves;
it doesn't decode MakerNotes (each manufacturer's private format), JUMBF/C2PA boxes or FlashPix; the quality
estimate is only meaningful on the libjpeg scale. For the bytes themselves, every segment opens in the Hex tool.
11The JpegFile library
lib/image/jpeg.js is a JavaScript module with no user interface; it imports
lib/image/exif.js for the Exif and MPF segments.
import { JpegFile } from "../../lib/image/jpeg.js";
| Member |
What it is |
| JpegFile.parse(bytes, options) |
Reads a JPEG from a Uint8Array; throws if it doesn't start with a marker. A missing SOI, EOI or
anything else wrong becomes a problem. options.embedded: false doesn't read inside
the embedded images. |
| JpegFile.isJpeg(bytes) |
Whether the bytes start with FF D8 FF. |
| jpeg.segments |
Every part in file order:
[{ marker, name, label, offset, length, dataOffset, dataLength, fill, info, problems }].
marker is the code after FF (null for the entropy-coded data, named
ECS, and for bytes that aren't a segment); offset and
length cover the whole segment from its FF; info is what it says,
decoded. |
| jpeg.frame |
The SOF:
{ name, type, process, coding, differential, precision, width, height, components: [{ id, name, horizontal, vertical, quantizationTable }], samplingFactors, subsampling, colorModel },
or null. |
| jpeg.scans |
[{ index, components: [{ id, name, dcTable, acTable }], spectralStart, spectralEnd, approximationHigh, approximationLow, description, restartInterval, data: { offset, length, restarts, expectedRestarts, restartsOutOfOrder, stuffedBytes, truncated } }].
|
| jpeg.quantizationTables · jpeg.quality |
[{ offset, id, precision, zigzag, values, usedBy, quality: { quality, exact, averageError } }]
(values row by row); { estimate, exact, tables }: the IJG quality, or
null. |
| jpeg.huffmanTables |
[{ offset, tableClass, id, counts, symbols, standard }]; standard
names the Annex K table it is, or is null. |
| JpegFile.huffmanCodes(table) |
The canonical code of each symbol: [{ symbol, length, code }], code as
a string of bits. |
| jpeg.exif |
{ tiffOffset, exif }: the first Exif segment, exif an
Exif (below); or null. |
| jpeg.xmp |
[{ text, extended, guid, complete }]: the XMP packet, and the reassembled extended
XMP. |
| jpeg.icc |
{ count, size, complete, header, description, tags }: the reassembled ICC profile,
or null. |
| jpeg.mpf |
{ tiffOffset, version, images: [{ index, type, typeName, format, size, offset, absoluteOffset, flags, representative, dependentParent, dependentChild }], exif },
or null. |
| jpeg.photoshop |
{ resources: [{ id, name, resourceName, offset, size }], iptc: [{ record, dataset, name, value }] },
or null. |
| jpeg.jfif · jpeg.adobe · jpeg.ducky · jpeg.comments |
What APP0 JFIF, APP14 Adobe and APP12 Ducky say (or null), and the COM texts
[{ text }]. |
| jpeg.restartInterval |
The last DRI interval, or 0. |
| jpeg.embedded |
JPEGs inside the file:
[{ kind, offset, length, isJpeg, image: { width, height, process, subsampling }, problems }]
— the Exif, JFXX and Photoshop thumbnails, the MPF images, and JPEGs after EOI. |
| jpeg.endOffset · jpeg.trailing |
Where the image ends;
{ offset, length, zeros, explainedBy, contents: [{ offset, what }] } of the bytes
after EOI (explainedBy: "MPF" when they are the MPF images), or null. |
| jpeg.problems |
What is wrong with the file as a whole. |
| jpeg.data(segment) · jpeg.extract(part) |
A segment's data bytes; the bytes [offset, offset + length) of a part such as an
embedded image (views into the file). |
| JpegFile.markerName(code) · JpegFile.ZIGZAG · JpegFile.MARKER_DESCRIPTIONS |
“SOF2”, “APP1”, “RST3”… for a code; the natural position of each zigzag index; what each fixed
marker is. |
const jpeg = JpegFile.parse(new Uint8Array(await file.arrayBuffer()));
console.log(jpeg.frame.width, jpeg.frame.height, jpeg.frame.process, jpeg.frame.subsampling);
if (jpeg.quality) {
console.log("quality about " + jpeg.quality.estimate + (jpeg.quality.exact ? " (libjpeg)" : ""));
}
const position = jpeg.exif ? jpeg.exif.exif.location() : null;
if (position) {
console.log("taken at", position.latitude, position.longitude);
}
for (const image of jpeg.embedded) {
const thumbnail = JpegFile.parse(jpeg.extract(image));
console.log(image.kind, thumbnail.frame.width, thumbnail.frame.height);
}
if (jpeg.trailing && !jpeg.trailing.explainedBy) {
console.log(jpeg.trailing.length + " bytes appended after EOI");
}
12The Exif library
lib/image/exif.js reads Exif metadata (and other TIFF-structured blocks such as MPF), for the
JPEG and PNG libraries. It has no dependencies.
import { Exif } from "../../lib/image/exif.js";
| Member |
What it is |
| Exif.parse(bytes) |
Reads Exif from its TIFF header (II*\0 or MM\0*): in a JPEG, 6 bytes
into the APP1 segment's data. |
| exif.directories |
[{ name, offset, entries, next }]: IFD0, Exif, GPS, Interoperability, IFD1. An
entry is { tag, name, type, typeName, count, offset, value, text }. |
| exif.find(name) · exif.location() |
The first entry with a tag name; the GPS position { latitude, longitude, altitude }
in degrees, or null. |
| exif.thumbnail · exif.littleEndian · exif.problems |
{ offset, length } of the embedded JPEG thumbnail (from the TIFF header); the byte
order; what couldn't be read. |
| Exif.TAGS · Exif.GPS_TAGS |
Tag number → name, for the TIFF, Exif, MPF and interoperability directories, and for GPS. |