How to get image width/height in next.js?
Asked Answered
D

1

7

In my app I allow users to upload their images. Upon uploading it goes into public folder, and in database there is only a direct link for future requests.

When displaying these images on the page I encounter a problem. Image component wants to know height and width of each image. And so I want to know it too.

What are the available options for the workflow in this situation? Both processing while uploading and while requesting will work for me.

Docker answered 26/5, 2021 at 22:29 Comment(4)
Have you considered using layout="fill" rather than providing dimensions?Leavings
@Leavings I tried it, but it seems like too much trouble to work properly. With the same result and far less amount of effort I can use image component from SemanticUI library, which I use in my project. As of now, I consider Image to do more harm than good.Docker
@Leavings layout="fill" hass been depreciatedInefficient
@Leavings has it? Its in the docs to use it for responsive layoutsDextrous
F
1

You can use image-size npm module:

npm install image-size --save

then:

var sizeOf = require('image-size');
var dimensions = sizeOf('./sample.jpg');
console.log(dimensions.width, dimensions.height);

from: How to check an image dimensions using js or node

Foggia answered 27/10, 2021 at 2:40 Comment(1)
image-size depends on fs. It doesn't work if you run Next.js on edge runtime.Dewyeyed

© 2022 - 2024 — McMap. All rights reserved.