Dynamically importing local images for use in next/image
#52744
Replies: 6 comments 2 replies
-
|
\cc @leerob @delbaoliveira (apologies for random tagging, but because you guys maintain the docs maybe you can clarify the docs part of it). |
Beta Was this translation helpful? Give feedback.
-
|
@schardev Hi, have you found an answer? I would like to know how to import local images based on path from frontmatter as well. |
Beta Was this translation helpful? Give feedback.
-
|
@ibqn |
Beta Was this translation helpful? Give feedback.
-
|
I try some difference things, and found another solution (not ideal): In mdx: After you need to put image Mdx component: img: (props) => {
return (
// eslint-disable-next-line jsx-a11y/alt-text
<Image
sizes="100vw"
style={{ width: "100%", height: "auto" }}
width={0}
height={0}
className="my-12"
{...(props as ImageProps)}
/>
);
},But yes, it's not helping with width & height |
Beta Was this translation helpful? Give feedback.
-
|
I found something that seems to do a bit better with MDX images, and adds a layer blur on load, which is beneficial for my scenario. import styles from './styles.module.css';
import { ComponentPropsWithoutRef } from 'react';
import Image, { ImageProps } from 'next/image';
import path from 'path';
import sharp from 'sharp';
interface ImgProps extends ComponentPropsWithoutRef<'img'> {
src: string;
}
export default async function Img(props: ImgProps) {
const imagePath = path.join(process.cwd(), 'public', props.src);
const sharpImage = sharp(imagePath);
const placeholder = await sharpImage.resize(10).toBuffer();
const base64 = placeholder.toString('base64');
const blurDataURL = `data:image/png;base64,${base64}`;
return (
<Image
sizes='100%'
quality={100}
placeholder='blur'
blurDataURL={blurDataURL}
width={2048}
height={1365}
className={styles.properties}
{...(props as ImageProps)}
/>
);
}Change to your liking, but this is what my component looks like, and works well on MDX renders: Obviously the |
Beta Was this translation helpful? Give feedback.
-
|
I made this component to solve precisely this issue. It's based on the one that Rauch himself uses on his blog page. Make sure that your VERCEL_PROJECT_PRODUCTION_URL makes sense and is publicly available. import NextImage from 'next/image';
import sizeOf from "image-size";
interface ImageProps {
src: string;
alt?: string;
width?: number;
height?: number;
}
export const Image: React.FC<ImageProps> = async ({ src, alt, width, height }) => {
const isExternal = src.startsWith('http');
if (width == null || height == null) {
const absoluteSrc = isExternal ? src : getAbsolutePath(src)
let imageBuffer = Buffer.from(await fetch(absoluteSrc).then(res => res.arrayBuffer()));
const size = sizeOf(imageBuffer!);
width = size.width;
height = size.height;
}
return <NextImage alt={alt ?? ""} src={src} width={width} height={height} />
};
export function getAbsolutePath(relativePath: string) {
const baseUrl = process.env.VERCEL_PROJECT_PRODUCTION_URL && `https://${process.env.VERCEL_PROJECT_PRODUCTION_URL}` || 'http://localhost:3000';
const cleanRelativePath = relativePath.startsWith('/') ? relativePath.slice(1) : relativePath;
return `${baseUrl}/${cleanRelativePath}`;
} |
Beta Was this translation helpful? Give feedback.
Uh oh!
There was an error while loading. Please reload this page.
-
So let's say I have a bunch of MDX files that I want to statically render that contains local images. I want them to properly optimize first using
next/image, so what are my options?In the official docs it says:
except ... I can still use it and
next/imageworks (almost) as expected. See for example the below (overly simplified) code snippet:This works and
next/imageproperly generatessrcsetfrom the local image (except for detecting/setting the width and height automatically). Then why does it says in the docs that dynamic imports are not supported? Are they not supported in SSR only but works totally fine when used with ISR?Currently it doesn't detect width / height and I can only think of reading the image file using
node:fsand setting width / height based on the image buffer using any library. Let me know if there's a better approach for this.Beta Was this translation helpful? Give feedback.
All reactions