How to get an image width and height using Node

By

Learn how to get an image width and height in Node.js with image-size 2.x using imageSize() for buffers and imageSizeFromFile() for local paths.

~~~

To get the width and height of an image in Node.js, use the image-size npm module. You pass it a buffer or a file path, and it gives you back the dimensions.

Node has no built-in API to read image data, so we need a module for this. image-size is a good pick because it only reads the header of the file, where the dimensions are stored. It doesn’t load the whole image into memory, so it’s fast even on large files.

You need to know the location of the image on the file system. If it’s an image from the Internet, you can save it to the system tmp folder first, or fetch it into a buffer.

Install the module:

npm install image-size

For a local file, use the async helper from image-size/fromFile:

import { imageSizeFromFile } from 'image-size/fromFile'

const { width, height } = await imageSizeFromFile('/Users/flavio/photos/sunset.jpg')

console.log(width, height) //1920 1080

The object returned also contains a type property, which tells you the image format:

const dimensions = await imageSizeFromFile('/Users/flavio/photos/sunset.jpg')

console.log(dimensions.type) //'jpg'

This is handy when you accept uploads and want to know what you’re dealing with. The module supports the common formats: JPEG, PNG, GIF, WebP, SVG, and several others.

Working with remote images

Instead of saving a remote image to disk, you can fetch it and pass a Buffer to imageSize():

import { imageSize } from 'image-size'

const res = await fetch('https://flaviocopes.com/img/og.png')
const buffer = Buffer.from(await res.arrayBuffer())

const { width, height } = imageSize(buffer)

This skips the file system entirely, which is nice in a serverless environment where you might not want to write temporary files.

What if the file is not an image?

Be careful: both helpers throw if the path doesn’t exist or if the file is not an image they can parse. A truncated download or a file with a wrong extension will crash your program if you don’t handle it.

Wrap the call in a try/catch:

try {
  const { width, height } = await imageSizeFromFile('/Users/flavio/photos/sunset.jpg')
  console.log(width, height)
} catch (err) {
  console.error('could not read image dimensions', err)
}

This matters most when the images come from users. Never assume an uploaded file is a valid image just because its name ends in .jpg.

Tagged: Node.js · All topics

Want me to talk about your product? You can sponsor this site.

~~~

Related posts about node: