You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Deno下TypeScript使用blurhash报错:宽高与像素数组不匹配如何解决

在Deno环境中解决Blurhash尺寸不匹配问题

问题出在Blurhash的encode函数要求输入的像素数组是RGBA格式(每个像素占4字节:红、绿、蓝、透明度),如果你的图片是RGB格式(每个像素3字节,无透明度通道),数组总长度为width*height*3,但函数预期长度是width*height*4,因此触发Width and height must match the pixels array错误。

由于Deno无法使用sharp库,你可以手动将RGB格式的像素数组转换为RGBA格式,给每个像素补充不透明的alpha通道(值为255):

实现RGB转RGBA的工具函数

function rgbToRgba(rgbPixels: Uint8ClampedArray, width: number, height: number): Uint8ClampedArray {
  const rgbaPixels = new Uint8ClampedArray(width * height * 4);
  let rgbaIndex = 0;
  // 遍历RGB数组,每3字节对应一个像素
  for (let i = 0; i < rgbPixels.length; i += 3) {
    rgbaPixels[rgbaIndex++] = rgbPixels[i];     // 红色通道
    rgbaPixels[rgbaIndex++] = rgbPixels[i + 1]; // 绿色通道
    rgbaPixels[rgbaIndex++] = rgbPixels[i + 2]; // 蓝色通道
    rgbaPixels[rgbaIndex++] = 255;             // 透明度通道(不透明)
  }
  return rgbaPixels;
}

修改原有代码

在调用encode前判断像素数组格式,必要时转换:

const response = await fetch(url);
if (!response.body) {
  throw new Error("Body null");
}

const arrayBuffer = await response.arrayBuffer();
let clamped = new Uint8ClampedArray(arrayBuffer);

// 检查是否为RGB格式(长度符合width*height*3)
if (clamped.length === width * height * 3) {
  clamped = rgbToRgba(clamped, width, height);
}

// 现在可以正常调用encode
const blurhash: string = encode(clamped, width, height, 4, 4);

内容的提问来源于stack exchange,提问作者progNewbie

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.28 05:15:13