Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get image height and width properties in Next.js?

I just want to know how can we let an image take its own height and width using <Image> component in Next.js, instead of defining height and width by ourselves?

like image 572
khukuk Avatar asked Oct 17 '25 07:10

khukuk


1 Answers

Beginning from Next.js v11, you can simply do:

import Image from 'next/image';
import foo from 'path/to/foo.png';

// ...

<Image src={foo} alt="" /> // <-- no need to pass height/width

In the above example, foo will be an object containing src, height, width (and optionally blurDataURL). So, if you want to access them, you can do stuff like foo.height, etc.


Also, there are a few hacks that may interest you:

  1. Use layout="fill" and pass a handler to onLoadingComplete, where you will get naturalWidth and naturalHeight. Then you can set the state to adjust the container accordingly. But this approach is not recommended as it will likely increase CLS.

  2. In data fetching methods [getStaticProps (static generation) / getServerSideProps (SSR)], read your image files and pass their dimensions as a prop to your components. SSR may cause an overhead on your server resources, but that can be minimized significantly by caching.

  3. Simply use your good old img tag. Again not recommended, but will work if your files are already optimized. ESLint may throw some warning depending on your configuration, you would need to disable those rules.


PS: Just check once if your use-case can be handled by layout="fill" (without updating state).

Just a clarification - on older threads on SO, GitHub, etc., you may see an unsized prop being passed to next/image. It was deprecated in Next.js v10, and removed in v11. So, its probably not gonna work for you.


References:

  • https://nextjs.org/docs/api-reference/next/image
  • https://nextjs.org/docs/basic-features/data-fetching
  • https://nextjs.org/docs/going-to-production
  • Get the width and height of an image in node.js
  • Next.js build fails using <img> tag
  • How to use Image component in Next.js with unknown width and height
  • https://web.dev/cls
  • https://web.dev/time-to-first-byte

A sample implementation of the second hack:

import fs from "fs";
import path from "path";

import Image from "next/image";
import probe from "probe-image-size";

const IndexPage = ({ mountains }) => (
  <Image
    src="/mountains.jpg"
    height={mountains.height}
    width={mountains.width}
    alt="Mountains"
  />
);

const getStaticProps = async () => {
  const mountains = await probe(
    fs.createReadStream(path.join(process.cwd(), "public/mountains.jpg"))
  );
  return { props: { mountains } };
};

export default IndexPage;
export { getStaticProps };
like image 200
brc-dd Avatar answered Oct 20 '25 07:10

brc-dd



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!