nodejs sharp get image size
To get the image size using the Node.js package "sharp," you can follow these steps:
- Install the "sharp" package by running the following command in your terminal:
npm install sharp
- Import the "sharp" module in your Node.js script by adding the following line of code at the beginning:
const sharp = require('sharp');
- Load the image file by specifying its path using the
sharp
module'sinput
method:
sharp('path/to/image.jpg')
- Retrieve the metadata of the image using the
metadata
method of thesharp
object:
sharp('path/to/image.jpg')
.metadata()
- 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
});
- Optional: If you want to resize the image as well, you can chain the
resize
method before themetadata
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.