模糊数据 URL 的 Nextjs 数据 URL

J. *_*Doe 4 javascript uri image node.js next.js

在 NextJS 11 中,我们可以使用Image带有模糊占位符的组件。如果我们想将它与动态图像一起使用,我们必须使用blurDataURL,它是一个数据URL。

我想获取原始图像并将其缩小为 10x10 像素。当我尝试使用公共文件夹中已创建的其他图像时,fs.readFileSync('http://localhost:3000/1blur.png','base64')但出现此错误Error: ENOENT: no such file or directory, open 'http://localhost:3000/1blur.png',并且当我尝试打开该文件时,它正在我的导航器中工作。

所以,我有两个问题:

  • 为什么我有错误?
  • 如何动态地将原始图像转换为可与 Data URL 一起使用的 10x10 模糊图像?

谢谢 !

小智 7

您可以编写自己的自定义乐趣,并使用占位符图像作为 svg src。我通过这样做实现了

export default function TestComponents({bannerImage}) {
  const styles = ['bg-primary', 'bg-blue'];
  const newImageSrc = bannerImage.toString().replace(/[()]/g, '');
    const convertImage = (w, h) => `
  <svg width="${w}" height="${h}" version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
    <defs>
      <linearGradient id="g">
        <stop stop-color="#333" offset="20%" />
        <stop stop-color="#222" offset="50%" />
        <stop stop-color="#333" offset="70%" />
      </linearGradient>
    </defs>
    <rect width="${w}" height="${h}" fill="#333" />
    <rect id="r" width="${w}" height="${h}" fill="url(#g)" />
    <animate xlink:href="#r" attributeName="x" from="-${w}" to="${w}" dur="1s" repeatCount="indefinite"  />
  </svg>`;

  const toBase64 = (str) =>
    typeof window === 'undefined'
      ? Buffer.from(str).toString('base64')
      : window.btoa(str);

  return (
    <div
      
      className="bg-white rounded-lg md:space-x-6 space-y-6 text-center shadow-lg  group my-4  hover:-translate-y-3 eas-in-out duration-500 cursor-pointer"
    >
      <div className="relative">
        <Image
          src={newImageSrc}
          alt="Picture of the author"
          layout="responsive"
          placeholder="blur"
          width={700}
          height={475}
          className="rounded-t"
          blurDataURL={`data:image/svg+xml;base64,${toBase64(
            convertImage(700, 475)
          )}`}
        />
</div>
</div>
)
}
Run Code Online (Sandbox Code Playgroud)