nodejs sharp get image size

To get the image size using the Node.js package "sharp," you can follow these steps:

  1. Install the "sharp" package by running the following command in your terminal:
npm install sharp
  1. Import the "sharp" module in your Node.js script by adding the following line of code at the beginning:
const sharp = require('sharp');
  1. Load the image file by specifying its path using the sharp module's input method:
sharp('path/to/image.jpg')
  1. Retrieve the metadata of the image using the metadata method of the sharp object:
sharp('path/to/image.jpg')
  .metadata()
  1. Handle the metadata by attaching a callback to the then method to access the width and height of the image:
sharp('path/to/image.jpg')
  .metadata()
  .then(metadata => {
    const width = metadata.width;
    const height = metadata.height;
    // Use the width and height as needed
  })
  .catch(err => {
    // Handle any potential errors
  });
  1. Optional: If you want to resize the image as well, you can chain the resize method before the metadata method and specify the desired dimensions:
sharp('path/to/image.jpg')
  .resize(800, 600) // Resize to 800x600 pixels
  .metadata()
  .then(metadata => {
    const width = metadata.width;
    const height = metadata.height;
    // Use the resized width and height as needed
  })
  .catch(err => {
    // Handle any potential errors
  });

That's it! Following these steps, you'll be able to use the "sharp" package in Node.js to get the size of an image and even resize it if desired.