Lightweight & Performant Image Size Detection Library – image-dimensions

Category: Image , Javascript | November 25, 2025
Authorsindresorhus
Last UpdateNovember 25, 2025
LicenseMIT
Tags
Views43 views
Lightweight & Performant Image Size Detection Library – image-dimensions

image-dimensions is a lightweight JavaScript utility that extracts width, height, and format from image files with minimal resource consumption. Weighs less than 2KB and has zero dependencies.

The library works across all modern JavaScript environments (browsers, Node.js, Bun, and Deno) and supports major image formats while reading only the necessary bytes instead of entire files.

Features:

  • Stream-Based Processing: Reads minimal data from streams, stopping as soon as dimensions are found.
  • Multiple Format Support: Handles PNG, JPEG, GIF, WebP, AVIF, and HEIF/HEIC image formats out of the box.
  • Memory-Safe Data Processing: Accepts pre-loaded Uint8Array buffers for scenarios where image data already exists in memory.
  • CLI Tool Included: Provides a command-line interface for quick dimension checks during development or in build scripts.

Use Cases:

  • Remote Image Validation: Check dimensions of user-uploaded images from CDN URLs before displaying them.
  • Responsive Image Processing: Determine source image dimensions during build pipelines to generate appropriate srcset attributes without loading full assets into memory.
  • Content Management Systems: Validate image dimensions during upload flows to enforce size requirements before accepting files from users.
  • Performance Monitoring Tools: Analyze image dimensions across websites without downloading complete image data during audits.

How To Use It:

1. Install the package via npm.

# NPM
$ npm install image-dimensions

2. Stream-based dimension detection:

//  Works with fetch responses in browsers:
import {imageDimensionsFromStream} from 'image-dimensions';
// Fetch an image URL and extract dimensions from the response stream
const url = 'https://example.com/photo.png';
const {body} = await fetch(url);
// The stream will be consumed incrementally until dimensions are found
const result = await imageDimensionsFromStream(body);
console.log(result);
// Output: {width: 1920, height: 1080, type: 'png'}
// For Node.js file system access:
import {createReadStream} from 'node:fs';
import {imageDimensionsFromStream} from 'image-dimensions';
// Convert Node.js ReadStream to Web ReadableStream
const stream = ReadableStream.from(createReadStream('photo.png'));
const dimensions = await imageDimensionsFromStream(stream);
console.log(dimensions);
// Output: {width: 1920, height: 1080, type: 'png'}

3. Use imageDimensionsFromData when working with canvas exports, file upload ArrayBuffers, or any scenario where the complete image already exists in memory.

import {imageDimensionsFromData} from 'image-dimensions';
// Process a Uint8Array buffer directly
const imageBuffer = await fetchImageAsBuffer();
const dimensions = imageDimensionsFromData(imageBuffer);
console.log(dimensions);
// Output: {width: 1920, height: 1080, type: 'png'}

4. The package also includes a CLI that allows you to determine the image dimensions directly in your terminal.

npx image-dimensions example.png
# Output: 1280x960

FAQs:

Q: Does this library work with images behind authentication or CORS restrictions?

A: The library itself processes whatever stream or data you provide. If you can fetch the image using credentials or CORS-enabled requests, you can pass the resulting stream to imageDimensionsFromStream. Authentication and CORS handling happen at the fetch layer before this library receives data.
Q: Why does the function return undefined instead of throwing errors for invalid images?
A: The undefined return pattern allows graceful handling of unrecognized formats or corrupted data. You can check the return value and implement fallback logic without wrapping every call in try-catch blocks. This works well when processing mixed content where some files might not be images.

Q: Can I use this to validate image dimensions before upload completion?
A: In browsers, you can create a ReadableStream from a File object and check dimensions as the file is being read, but the browser still needs to read the header bytes locally. For true server-side validation during upload, you’d need to stream the upload data through a server endpoint that uses this library to check dimensions before storing the file.

Q: How does stream processing handle slow network connections?
A: The library waits for sufficient chunks to accumulate before attempting dimension extraction. On slow connections, it simply takes longer to receive the necessary header bytes. The function will resolve once enough data arrives, regardless of connection speed.

Q: What happens if I pass a Buffer instead of Uint8Array in Node.js?
A: The library explicitly converts Buffer inputs to Uint8Array to prevent compatibility issues on Node.js 20 and later.

You Might Be Interested In:


Leave a Reply