问题描述
这是我的用例:
来自:https://nextjs.org/docs/api-reference/next/image
要渲染图像,next/image
要求您定义尺寸,方法是直接在 <Image/>
元素上设置,或在父元素上设置。这很好,因为它可以防止在图像加载阶段发生任何布局偏移。
但由于每张图片都有自己的尺寸,我可以为每张图片使用相同的尺寸。
这就是我需要的结果。
我怎样才能做到这一点?
我目前的想法:
上传图片时,我还必须保存其尺寸。在我开始使用 next/image
之前,我会简单地保存图像 src
。现在我必须保存如下内容:
post: {
images: [
{
src: "https://.../image1.jpeg",width: X,// SHOULD SAVE WIDTH
height: Y // AND HEIGHT
}
]
}
所以我将能够像这样渲染它:
const image = post.images[0];
return(
<Image
src={image.src}
width={image.width}
height={image.height}
/>
);
这是应该做的吗?有没有更简单的解决方案?
解决方法
我在问题中描述的方法正是我最终要做的。
我创建了这个函数来在上传前读取图像尺寸:
type ImageDimensions = {
width: number,height: number
}
export const getImageDimensions = (file: File) : Promise<ImageDimensions> => {
return new Promise((resolve,reject) => {
try {
const url = URL.createObjectURL(file);
const img = new Image;
img.onload = () => {
const { width,height } = img;
URL.revokeObjectURL(img.src);
if (width && height)
resolve({ width,height });
else
reject(new Error("Missing image dimensions"));
};
img.src=url;
}
catch(err) {
console.error(err);
reject(new Error("getImageDimensions error"));
}
});
};
所以现在每个图像都至少保存了以下属性:
image: {
src: string,width: number,height: number
}
我就是这样渲染的:
<Image
src={image.src}
width={image.width}
height={image.height}
/>
它按预期工作。