Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can we get height and width of image using sharp?

Tags:

node.js

sharp

I am using sharp to resize bulk of image. So I am resizing them to 500px by preserving their aspect ratio. Also I want to resize height to 500px and auto resize width if height is greater than width and vice versa. To do that I need to get image, height from Image buffer. I know there are pretty number of packages available to do so. But I was hoping if I can do that using sharp buffer itself.

like image 328
classydraught Avatar asked Sep 12 '25 15:09

classydraught


2 Answers

Yes you can get the width and height of an image with sharp by using the metadata() function :

const image = sharp(file.buffer)
const metadata = await image.metadata()
console.log(metadata.width, metadata.height)

You can get a lot more information from metadata , here is the documentation : https://sharp.pixelplumbing.com/api-input#metadata

like image 128
Stephane L Avatar answered Sep 15 '25 04:09

Stephane L


To get the dimensions that are recorded in the header of the input image:

const image = await sharp(file.buffer);
const metadata = await image.metadata();
console.log(metadata.width, metadata.height);

However, operations like image.resize(...) will not affect the .metadata(). To get the dimensions after performing operations on the image, use .toBuffer({ resolveWithObject: true }):

const image = await sharp(file.buffer);
const resizedImage = image.resize(640);
const { info } = await resizedImage.png().toBuffer({ resolveWithObject: true });
console.log(info.width, info.height);
like image 29
jameshfisher Avatar answered Sep 15 '25 04:09

jameshfisher