如何在Node.js中将彩色图像(jpg、jpeg、png)转换为黑白或灰度

3

我尝试使用了所有支持灰度处理的npm包,但是没有一个能正常工作。 其中一些可以工作,但质量会降低。 有一个很好的灰度处理包叫做image-grayscale,但问题在于如果其中一个src图像文件(例如/image.gpg)损坏,则根据promise代码停止继续执行。 下面的代码就是问题所在。

 globby(['./upload/*.*','!./upload/*.ico','!./upload/*.gif', '!./upload/*.txt']).then(function (paths) {
            return Promise.all(paths.map(function (e) {
                    return imageGrayScale(e, {logProgress: 1})                                      }));
                        }).then(function (val) {


   // if one of the file in directory is corrupted then promise is rejected and my code stooped  and i cant do  anything further

 })

请告诉我如何处理错误承诺以让代码继续执行下去。或者是否有类似回调的解决方案。

我应该前往其他模块,还是可以编写自己的算法来实现灰度?请告诉我如何将图像的颜色转换为黑白。

1个回答

7
我之前成功地使用过Jimp,所以你可以考虑使用它。
文档中提供的一个示例:
Jimp.read("file.png", (err, image) => {
    if (err) throw err;
    image.greyscale().write("image.png");
});

2
应该是一个被接受的答案 - jimp 提供了许多图像操作,迄今为止似乎比其他库更为稳健。 - abhishake
您,值得点赞。 - Sebastien H.

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接