How to get an image width and height using Node

By

Learn how to get an image width and height in Node.js using the image-size npm module and its sizeOf() function, which reads the file from its location.

~~~

To get the width and height of an image in Node.js, use the image-size npm module. You pass it the file location, 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.

Install the module:

npm install image-size

Then use it like this:

import sizeOf from 'image-size'

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

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

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

const dimensions = sizeOf('/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 directly to sizeOf():

import sizeOf from 'image-size'

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

const { width, height } = sizeOf(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: sizeOf() throws if the path doesn’t exist or if the file is not an image it 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 } = sizeOf('/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
~~~

Related posts about node: