Next.js Discord

Discord Forum

Optimising local "dynamic" images

Unanswered
Spectacled bear posted this in #help-forum
Open in Discord
Spectacled bearOP
I have a file with image paths. All these images are in my public folder.
I have a CustomImage component with is basically just an Image component with some wrappers. These CustomImage components take an image path from the file as a prop. They are also only available on statically rendered pages.

I want to create an Image components containing each of these images. I can simply add the image paths to the Image component src prop, however I also have to provide a width and height, which I do not know.

import Image from "next/image";

export default function CustomImage({
  src,
  alt,
  caption,
}: {
  src: string;
  alt?: string;
  caption?: string;
}) {
  return (
    <figure className={`flex justify-center w-full ${className}`}>
      <div className="flex justify-center w-full max-height-[80vh]">
        <Image
          loading="lazy"
          width={2048}
          height={2048}
          src={src}
          alt={alt ? alt : ""}
          className="w-full max-w-full rounded-xl"
        />
      </div>
      {caption ? <figcaption>{caption}</figcaption> : null}
    </figure>
  );
}


All images are available at build time, except that I can't import them all one by one statically. (unless there is a way to sort of automate it?)

I would like to provide the Image component with accurate width and height for the given image. Right now I just have some random big value.
These images are kinda random and so I don't know their aspect ratios ahead of time.

I tried to somehow load the images using js and use that to calculate the aspect ratio to then provide accurate width and height prop values to the Image component.

The image file paths come from an .mdx file.

So how can I calculate accurate width and height values for images for which I only know the paths, before I render the page?

0 Replies