Categories: CSSScriptWeb Design

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.

The post Lightweight & Performant Image Size Detection Library – image-dimensions appeared first on CSS Script.

rssfeeds-admin

Share
Published by
rssfeeds-admin

Recent Posts

‘She’s a Killer’ – Daredevil: Born Again’s Vincent D’Onofrio on Karen Page’s Dark Side

When Daredevil: Born Again debuted last year, many fans weren’t particularly happy with the way…

55 minutes ago

McDonald’s Introduces a ‘Pro Gamer Menu’ With an Arch-Shaped Device That Will Keep You From Going AFK While You Eat, But It’s Only Available in Türkiye

McDonald's has introduced a brand-new Pro Game Menu and an 'Archie' device that will keep…

55 minutes ago

Genius RollerCoaster Tycoon 2 Player Makes Longest Rollercoaster Ever Built, Manipulates Guests Into Staying Just Happy Enough to Ride It for 1.947 x 10²²⁷ Years

A RollerCoaster Tycoon 2 superfan has created what is believed to be the longest rollercoaster…

56 minutes ago

Democratic states sue Trump over mail-in ballot order, joining rush to courts

Baskets of ballots sit at a new ballot processing center in Thurston County, Washington, on…

2 hours ago

Free bus rides in Beloit for Wisconsin primary election on April 6

In a bid to encourage voter turnout for Wisconsin's primary election, the city of Beloit…

2 hours ago

Dari Ripple in South Beloit opens for the season

The Dari Ripple in South Beloit has officially opened its doors for the season.

2 hours ago

This website uses cookies.