使用 blurhash 制作的精美图片占位符
几周前,我玩了玩Wolt iOS 应用,它处理图片加载和占位符的方式给我留下了深刻的印象。一番寻找之后,我终于找到了Blurhash。
我为什么需要它?
Blurhash 可以帮助将无聊的图像占位符转换为更多的东西。
与 TypeScript 和 React 一起使用
安装
yarn add blurhash
对图像进行编码
import { encode } from 'blurhash';
const loadImage = async (src: string): Promise<HTMLImageElement> =>
  new Promise((resolve, reject) => {
    const img = new Image();
    img.onload = () => resolve(img);
    img.onerror = (...args) => reject(args);
    img.src = src;
  });
const getImageData = (image: HTMLImageElement): ImageData => {
  const canvas = document.createElement('canvas');
  canvas.width = image.width;
  canvas.height = image.height;
  const context = canvas.getContext('2d');
  context.drawImage(image, 0, 0);
  return context.getImageData(0, 0, image.width, image.height);
};
const encodeImage = async (url: string) => {
  const image: HTMLImageElement = await loadImage(url);
  const imageData: ImageData = getImageData(image);
  return encode(imageData.data, imageData.width, imageData.height, 4, 4);
};
将 blurhash 与图像一起存储
当将图像存储到 S3 存储桶时,我通常会对来自 S3 的图像运行编码函数,并将其与图像 URL 一起存储在数据库中,以便更容易。
我个人将图像存储在它自己的对象表示中,如下所示:
...
"image": {
  "url": "https://project-uploads.s3.amazonaws.com/i/...",
  "blurhash": "LKO2?U%2Tw=w]~RBVZRi};RPxuwH"
}
...
与 React 一起使用
将哈希值存储在服务器上后,就可以更轻松地将其与 React 一起使用,而无需使用react-blurhash进行任何手动解码。
import { BlurhashCanvas } from 'react-blurhash';
<Blurhash
  hash='<image_hash>'
  width={400}
  height={300}
  resolutionX={32}
  resolutionY={32}
/>
注意:您也可以手动解码哈希,查看blurhash 文档以了解更多详细信息
在线实验!
如果您想亲自尝试一下,可以使用在线生成器。
祝您编码愉快🎉
文章来源:https://dev.to/karanpratapsingh/amazing-image-placeholders-with-blurhash-11ok 后端开发教程 - Java、Spring Boot 实战 - msg200.com
            后端开发教程 - Java、Spring Boot 实战 - msg200.com
          
