Image width and height in Nodejs| image-size npm library

In my previous tutorials, Discussed about how to get image width and height in JavaScript

In this tutorial, we are going to discuss about how to get Image size in Nodejs application.

In Nodejs, We have different ways we can get image size using npm libraries and Inbuilt API’s

This tutorials talks about image-size npm library with example

This library supports all images of different types - PNG,BMP, ICO, SVG and JPEG

install image-size npm library

Let’s first create a node application called imagedimension

First create a imagedimension directory

mkdir imagedimension
cd imagedimension

next run npm init -y command to initialize application in the current folder

npm init -y

This will create a package.json file in the application root directory

next install image-size library using npm install command

npm i image-size --save
yarn add image-size

image-size dependency added in package.json and installs dependency to node_modules of an application.

We can write a asynchronous and synchronous code to get dimension of an image.

Create a main.js file ,add following lines of javascript code Here is an simple example for getting image width and height main.js

var imageSize = require('image-size');
var imageDimensions = imageSize('./demo.jpg');
console.log(typeof imageDimensions); // Image
console.log(imageDimensions.width); // 6000
console.log(imageDimensions.height); // 4000

this is synchronous code and straightforward way of getting image dimension

Let’s see how asynchronous way of image dimension example

var imageSize = require('image-size');

imageSize('./demo.png', function(err,dimension){

        console.log('error in reading image')
    console.log(typeof imageDimensions); // Image
console.log(imageDimensions.width); // 6000
console.log(imageDimensions.height); // 4000

err is an returned if any error occurred in reading image file dimension is returned for successful operation and returns width and height

Join 6,000 subscribers and get a daily digest of full stack tutorials delivered to your inbox directly.No spam ever. Unsubscribe any time.

Similar Posts
You'll get a notification every time a post gets published here.