【问题标题】:How to render images of unknown dimensions using next/image from Next.js?如何使用 Next.js 中的 next/image 渲染未知尺寸的图像?
【发布时间】:2021-07-31 16:19:07
【问题描述】:

这是我的用例:

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

发件人: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}
  />
);

这是应该怎么做的吗?有没有更简单的解决方案?

【问题讨论】:

    标签: reactjs next.js nextjs-image


    【解决方案1】:

    我在问题中描述的方法正是我最终所做的。

    我创建了这个函数来在上传之前读取图像尺寸:

    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}
    />
    

    它按预期工作。

    【讨论】:

      猜你喜欢
      • 2022-06-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-06-05
      • 1970-01-01
      • 2022-01-27
      • 1970-01-01
      • 2016-08-01
      相关资源
      最近更新 更多