node.jssharp

Can we get height and width of image using 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.


Solution

  • 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