Read image width and height without decoding, in Node
You can read an image's width and height from its first few hundred bytes, without decoding a single pixel. For PNG, GIF and WebP the numbers sit within the first 32 bytes. For a 9.8 MB JPEG they sat within the first 672
You can read an image's width and height from its first few hundred bytes, without decoding a single pixel. For PNG, GIF and WebP the numbers sit within the first 32 bytes. For a 9.8 MB JPEG they sat within the first 672. A 40-line parser answered in 0.113 ms; a full decode of the same file took 217.3 ms.
This matters at an upload endpoint: you can reject a 40,000 Γ 40,000 file before it costs you any memory.
Where do the four formats keep their size?
Each one stores it differently:
- PNG: the first chunk is always IHDR (PNG spec: width, height, bit depth, colour type). Width is a big-endian 32-bit integer at byte 16, height at byte 20.
- GIF: the logical screen descriptor. Width and height are little-endian 16-bit integers at bytes 6 and 8.
-
WebP: a RIFF container with three layouts. Lossy (
VP8), lossless (VP8L) and extended (VP8X) each pack the size differently. -
JPEG: no fixed offset. You walk the segments until you reach a start-of-frame marker (
SOF0toSOF15, minus a few), which holds height then width.
I did not trust my memory of these offsets, so the next section checks every one against sharp on real files.
What does the parser look like?
// dims.cjs
function dimensions(buf) {
// PNG: signature, then IHDR. Big-endian width at 16, height at 20.
if (buf.length >= 24 && buf.readUInt32BE(0) === 0x89504e47) {
return { format: 'png', width: buf.readUInt32BE(16), height: buf.readUInt32BE(20) };
}
// GIF: "GIF8", then little-endian width and height at 6 and 8.
if (buf.toString('latin1', 0, 4) === 'GIF8') {
return { format: 'gif', width: buf.readUInt16LE(6), height: buf.readUInt16LE(8) };
}
// JPEG: walk the segments until a start-of-frame marker.
if (buf[0] === 0xff && buf[1] === 0xd8) {
let i = 2;
while (i + 9 < buf.length) {
if (buf[i] !== 0xff) { i++; continue; }
const marker = buf[i + 1];
if (marker === 0xff) { i++; continue; }
const sof = marker >= 0xc0 && marker <= 0xcf && ![0xc4, 0xc8, 0xcc].includes(marker);
if (sof) return { format: 'jpeg', height: buf.readUInt16BE(i + 5), width: buf.readUInt16BE(i + 7) };
i += 2 + buf.readUInt16BE(i + 2); // skip this segment
}
return null; // not enough bytes yet: read more and retry
}
// WebP: RIFF....WEBP, then one of three chunk types.
if (buf.toString('latin1', 0, 4) === 'RIFF' && buf.toString('latin1', 8, 12) === 'WEBP') {
const kind = buf.toString('latin1', 12, 16);
if (kind === 'VP8 ') return { format: 'webp', width: buf.readUInt16LE(26) & 0x3fff, height: buf.readUInt16LE(28) & 0x3fff };
if (kind === 'VP8L') { const b = buf.readUInt32LE(21); return { format: 'webp', width: (b & 0x3fff) + 1, height: ((b >> 14) & 0x3fff) + 1 }; }
if (kind === 'VP8X') return { format: 'webp', width: buf.readUIntLE(24, 3) + 1, height: buf.readUIntLE(27, 3) + 1 };
}
return null;
}
The JPEG branch skips DHT (0xc4), JPG (0xc8) and DAC (0xcc), which sit in the same marker range but are not frame headers. The pointer jumps by each segment's length, so it never touches the compressed data.
Does it match sharp?
I ran it on the first 64 KB of each file and compared with sharp(file).metadata().
image-compressor-sample-camera-photo.jpeg {"format":"jpeg","height":2782,"width":4964} sharp 4964x2782 match
jpg-sample-photo-original.jpg {"format":"jpeg","height":1280,"width":1920} sharp 1920x1280 match
photo.png {"format":"png","width":800,"height":600} sharp 800x600 match
screen.png {"format":"png","width":3456,"height":22060} sharp 3456x22060 match
photo-lossy.webp {"format":"webp","width":1920,"height":1280} sharp 1920x1280 match
photo-lossless.webp {"format":"webp","width":1920,"height":1280} sharp 1920x1280 match
transparent-alpha.webp {"format":"webp","width":512,"height":512} sharp 512x512 match
IMG_7426.GIF {"format":"gif","width":373,"height":498} sharp 373x498 match
All 12 files I ran matched (eight are shown), including the three WebP layouts I produced with sharp (lossy, lossless, lossy with alpha). screen.png is a full-page screenshot, 3456 Γ 22060, and the parser still needed only 24 bytes.
How many bytes did it need?
I grew the prefix in 32-byte steps until dimensions() returned a result.
- PNG, WebP and GIF: the first 32-byte step was enough.
- The 1920 Γ 1280 JPEG: 192 bytes.
- The 9.8 MB camera JPEG: 672 bytes. It carries an ICC profile segment (474 bytes) ahead of the frame header.
A JPEG with a big EXIF block or an embedded thumbnail pushes the frame header further out. That is why the function returns null instead of guessing: read more bytes and call it again.
How much faster is it?
Median of 5 runs, in milliseconds. "Header" is reading 64 KB from disk plus the parse.
| File | Header | metadata() |
Full decode |
|---|---|---|---|
| camera.jpeg (9.8 MB) | 0.113 | 3.948 | 217.3 |
| photo-1920.jpg | 0.084 | 1.276 | 19.2 |
| screen.png (8.3 MB) | 0.076 | 2.836 | 265.2 |
| photo-lossy.webp | 0.138 | 1.435 | 41.8 |
| IMG_7426.GIF | 0.043 | 0.592 | 3.0 |
metadata() is already lazy. It reads the header and stops, which is why it is far cheaper than a decode. The hand-rolled parser is about 10 to 37 times faster than metadata() on these files, but both are tiny next to the decode. Use sharp unless you handle many thousands of files per second, or you want the check before sharp is involved at all.
Note: the header is the file's claim, not the truth. The size says 4964 Γ 2782, and a truncated or hostile file may hold fewer pixels, or a different format behind a valid header. The parser tells you what to reject early. It does not tell you the file decodes.
What does EXIF orientation do to it?
Nothing, and that is the trap. I wrote a copy of the 800 Γ 600 test photo with EXIF orientation 6 (rotate 90Β°):
{"format":"jpeg","height":600,"width":800} 800 600 6 {"width":600,"height":800}
The parser and metadata() both say 800 Γ 600. The picture displays as 600 Γ 800, and sharp reports that under autoOrient. If you compare an upload against a pixel limit, the product is the same either way. If you check an aspect ratio, swap width and height when orientation is 5 to 8.
What about AVIF and HEIC?
I did not write those parsers. Their size lives in an ispe box inside nested ISO-BMFF boxes, and the walk is longer than a few offsets. Let sharp read those headers with metadata(), which stays cheap.
One measurement trap
sharp caches operations by default. My first decode timings for WebP and GIF looked absurdly low (1 ms and 3 ms) because repeat runs hit the cache. Call sharp.cache(false) before you time anything. The table above uses that setting.
For the format-detection side of the same bytes, see the image formats guide. For how we run measurements, see how we measure.
How I measured
- Node v24.22.0, sharp 0.35.4 (libvips 8.18.6), Apple M1 Pro, 2026-10-18.
- Files: the site's 4964 Γ 2782 camera photo, the 1920 Γ 1280 sample photo, the engine fixtures
photo.jpg,photo.png,screen.png,photo.webp, and three WebP files and one GIF I wrote or had on disk (IMG_7426.GIF, 2,817,469 bytes). - Timings: median of 5 runs,
sharp.cache(false). Full decode issharp(file).raw().toBuffer(). - Raw numbers:
measured.jsonin this folder.
What I did not test
AVIF, HEIC, TIFF, BMP and JPEG XL headers. Progressive and arithmetic-coded JPEGs beyond the marker list above. Files whose headers lie about their size.
I build Blinkimg, an image compressor and converter with a developer API. I wrote this article with help from an AI assistant (Claude), which ran the code on my machine; every number in it comes from those runs.
Originally published by Dev.to WebDev. Aggregated on AIWithGhost for educational purposes β full credit and traffic to the original publisher.