#Image natural width and height
1 messages · Page 1 of 1 (latest)
Hi @fathom hawk. I'm kapa.ai, your friendly support bot. I will try to answer your question by searching through the knowledge base. :wave:
To maintain the original aspect ratio of an image in Next.js, you can use the width and height props of the Image component. These props represent the rendered width and height in pixels, and they affect how large the image appears. If you want the image to maintain its original aspect ratio, you should set these props to the original width and height of the image.
Here is an example:
import Image from 'next/image'
export default function Page() {
return (
<div>
<Image
src="/profile.png"
width={500} // original width of the image
height={500} // original height of the image
alt="Picture of the author"
/>
</div>
)
}
(Source: Next.js Docs (https://nextjs.org/docs/pages/api-reference/components/image#required-props))
To get the natural width and height of an image when it's loaded, you can use the onLoadingComplete prop of the Image component. This prop accepts a function that is called when the image finishes loading. The function receives an object with the naturalWidth and naturalHeight properties, which represent the natural width and height of the image.
Here is an example:
<Image
src={imageLocation}
onLoadingComplete={(img) => console.log(img.naturalWidth, img.naturalHeight)}
layout="fill"
/>
(Source: Github Issue (https://github.com/vercel/next.js/issues/34697))