如何使用 Next.js 中的 next/image 渲染未知尺寸的图像?

问题描述

这是我的用例:

  • 我将在博文中添加图片
  • 我无法设置固定尺寸来渲染这些图像,因为每个图像可能都有独特的比例
  • 例如:我可能会上传 400 x 400 的方形图片400 x 200 的矩形图片

来自:https://nextjs.org/docs/api-reference/next/image

要渲染图像,next/image 要求您定义尺寸,方法是直接在 <Image/> 元素上设置,或在父元素上设置。这很好,因为它可以防止在图像加载阶段发生任何布局偏移。

但由于每张图片都有自己的尺寸,我可以为每张图片使用相同的尺寸。

这就是我需要的结果。

enter image description here

我怎样才能做到这一点?

我目前的想法:

上传图片时,我还必须保存其尺寸。在我开始使用 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}
/>

它按预期工作。

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...