【问题标题】:next/image loads very big imagesnext/image 加载非常大的图像
【发布时间】:2021-05-30 13:35:42
【问题描述】:

我在我的项目中使用 Next js 并使用 next/image 来加载图像。我的页面大约为1600px 宽,每行有3 个缩略图,宽度为500px,如下所示。

所以我需要 next/image 来加载 500px 宽度版本的缩略图,但它会加载具有 1600px 宽度的图像。

这是我用过的组件

import Image from 'next/image';

<Image
  src={article.thumbnail}
  width={500}
  height={277}
  layout="responsive"
/>

我的 next.config.js:

module.exports = {
  images: {
    domains: ['res.cloudinary.com'],
    deviceSizes: [320, 640, 660, 768, 1024, 1600],
    loader: 'cloudinary',
    path: 'https://res.cloudinary.com/pratiek/',
  }
};

接下来在 HTML 上给出的输出如下所示:

<div style="display:block;overflow:hidden;position:relative;box-sizing:border-box;margin:0">
   <div style="display:block;box-sizing:border-box;padding-top:55.400000000000006%"></div>
   <img 
    src="https://res.cloudinary.com/pratiek/f_auto,c_limit,w_1600,q_auto/strapi_7efe62d320.png" 
    decoding="async" 
    style="visibility: inherit; position: absolute; inset: 0px; box-sizing: border-box; padding: 0px; border: none; margin: auto; display: block; width: 0px; height: 0px; min-width: 100%; max-width: 100%; min-height: 100%; max-height: 100%;" 
    sizes="100vw" 
    srcset="
      https://res.cloudinary.com/pratiek/f_auto,c_limit,w_320,q_auto/strapi_7efe62d320.png 320w,
      https://res.cloudinary.com/pratiek/f_auto,c_limit,w_640,q_auto/strapi_7efe62d320.png 640w,
      https://res.cloudinary.com/pratiek/f_auto,c_limit,w_660,q_auto/strapi_7efe62d320.png 660w,
      https://res.cloudinary.com/pratiek/f_auto,c_limit,w_768,q_auto/strapi_7efe62d320.png 768w,
      https://res.cloudinary.com/pratiek/f_auto,c_limit,w_1024,q_auto/strapi_7efe62d320.png 1024w,
      https://res.cloudinary.com/pratiek/f_auto,c_limit,w_1600,q_auto/strapi_7efe62d320.png 1600w"
    />
</div>

我认为最后一行是输出有什么问题,它要求 1600px 视口上的 1600px 图像,但我需要 1600px 视口上的 500px 图像,我该如何得到?

【问题讨论】:

    标签: javascript reactjs next.js


    【解决方案1】:

    我认为这是由于

    layout="responsive
    

    根据 `next` 的文档:


    布局

    固定时,图像尺寸不会随着视口变化(无响应)而变化,类似于原生 img 元素。

    intrinsic时,图像将缩小尺寸以适应较小的视口,但保持原始尺寸以适应较大的视口。

    响应式时,图像将缩小尺寸以适应较小的视口,并按比例放大以适应较大的视口。

    填充时,图像的宽度和高度都会拉伸到父元素的尺寸,通常与 objectFit 属性配对。

    在此处了解更多信息:- next/image

    【讨论】:

    • 我确实希望它具有响应性,因为我希望它为较小的视口加载较低分辨率的图像。
    • 然后您可以尝试将样式(尺寸)添加到其父级&lt;div&gt;。这将限制图像的增长。确保只添加宽度,以免图像被拉伸。
    猜你喜欢
    • 2013-02-09
    • 2016-02-27
    • 2021-03-15
    • 1970-01-01
    • 1970-01-01
    • 2016-04-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多