How to reduce Image width and height in Nodejs| image-size npm library
In my previous tutorials, Discussed how to get image width and height in JavaScript
In this tutorial, we are going to discuss how to get Image size in the Nodejs application.
In Nodejs, We have different ways we can get image size using npm libraries and Inbuilt APIs
This tutorial talks about image-size npm library for 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 image dimension
First, create an image dimension directory
mkdir imagedimension
cd imagedimension
next run the npm init -y
command to initialize the application in the current folder
npm init -y
This will create a package.json file in the application root directory
next, install the image-size
library using the npm install command
npm i image-size --save
or
yarn add image-size
image-size
dependency is added in package.json and installs dependency to node_modules of an application.
We can write asynchronous and synchronous code to get the dimension of an image.
Create a main.js file, add the following lines of javascript code Here is a 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 a 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) {
if (err) {
console.log("error in reading image");
}
console.log(typeof imageDimensions); // Image
console.log(imageDimensions.width); // 6000
console.log(imageDimensions.height); // 4000
});
err is returned if any error occurred in reading an image file dimension is returned for successful operation and returns width and height