Color-Thief Node plugin error: "Image given has not completed loading"

Color-Thief Node plugin error: "Image given has not completed loading"

在 Node/Express 工作,我试图让 npm 包 color-thief 从图像中获取主色,但失败了,因为 "image given has not completed loading".

图片还是本地的,所以它不应该有这个特殊问题。除此之外,color-thief returns 一个承诺,我正在使用 async/await,所以它应该等待图像 花了多长时间加载而不是抛出错误。

下面是我的 SSCCE 代码:

const ColorThief = require('color-thief');

let colorThief = new ColorThief();

async function getDominantColor() {
    const img = 'public/img/seed/big-waves-2193828__340.webp';
    const dominantColor = await colorThief.getColor(img);
    console.log(dominantColor);
}

getDominantColor();

问题原来是插件显然不支持 .webp 个文件。

它在 .jpg.png 上运行良好,尽管 Documentation(不容易获得)没有明确说明它的文件类型 does/does 不支持。

我已经提交了关于该项目的 feature request on Github to either add support for webp or update the documentation with an explicit list of supported filetypes, but the author states at the very bottom of his blog

"In the short term I'm not planning on doing any more work on the script."

我只是想我会尽量避免将来使用它的其他人一些头痛和时间

根据上面的 R Greenstreet 回答,Color-Thief 不支持除 .jpg.png.
以外的其他格式 因此,要解决此问题,您需要即时转换图像。

我能找到的最快最方便的方法就是使用节点 sharp 模块。而代码本身只有几行...

const sharp = require('sharp');

let image = await sharp(imageData);
let imageData = await image.metadata();

if (imageData.format === 'webp') {
    image = await image.toFormat('png').toBuffer();
} else {
    image = await image.toBuffer();
}

我知道,这不是最佳解决方案,但如果你想要一个稳定的修复,这应该没问题。