Micro Thumbnail Blob

轻量级图像缩略图生成与 Blob 存储技术指南

什么是 Micro Thumbnail Blob?

Micro Thumbnail Blob 是一种利用浏览器原生能力(如 canvasBlob)将图像压缩为极小尺寸缩略图,并以二进制大对象(Blob)形式在内存或本地临时存储的技术。

它常用于上传前预览、节省带宽、提升用户体验,或作为缓存策略的一部分。

基本实现示例

以下是一个使用原生 JavaScript 生成缩略图并转为 Blob 的简单代码:

function createThumbnail(file, maxWidth = 64, maxHeight = 64) {
  return new Promise((resolve, reject) => {
    const img = new Image();
    const canvas = document.createElement('canvas');
    const ctx = canvas.getContext('2d');

    img.onload = () => {
      let { width, height } = img;
      if (width > height) {
        if (width > maxWidth) {
          height *= maxWidth / width;
          width = maxWidth;
        }
      } else {
        if (height > maxHeight) {
          width *= maxHeight / height;
          height = maxHeight;
        }
      }

      canvas.width = width;
      canvas.height = height;
      ctx.drawImage(img, 0, 0, width, height);

      canvas.toBlob(blob => {
        resolve(blob);
      }, 'image/jpeg', 0.7);
    };

    img.onerror = reject;
    img.src = URL.createObjectURL(file);
  });
}

应用场景