nodejs 对 png 图片的像素级别处理

使用node对图片的像素进行处理

这里使用常见的图片灰度处理为例子:

用到了 pngjs 的 npm 库,这个库可以将 png 的图片文件 Buffer 流,转换为 r g b a 为 255 的像素值, 同时也可以将 r g b a 的 255 像素值,转换为文件的 Buffer 流,然后写入文件。

例子:

const fs = require('fs'),PNG = require('pngjs').PNG;
// 根据参数获取文件名称
const pngFile=process.argv[2];
var outDir=pngFile.replace(".png","");

// 读取文件的r g b a 数据
function getImgData(p){
    return new Promise((resolve,reject)=>{
        fs.createReadStream(p)
            .pipe(new PNG({
                filterType: 4
            }))
            .on('parsed', function() {
                var data= new Buffer.alloc(4*this.width*this.height);
                this.data.copy(data);
                resolve({
                    data:data,
                    width:this.width,
                    height:this.height
                });
            }
        );
    })
}


// 将数据保存到文件
function ImgDataToSave(imgData){
    let {width,height,data} = imgData;
    var newPng=new PNG({
        filterType: 4,
        width:width,
        height:height
    });
    newPng.data = data;
    var dst = fs.createWriteStream('export/'+outDir+'.png');
    newPng.pack().pipe(dst);
}

// 获取图片后灰度处理
getImgData(pngFile).then((res)=>{
    let {width,height,data} = res;
    for(let i = 0; i < height; i++){
        for(let j = 0; j < width; j++){
            var idx = (width * i + j) << 2;
            var avg =  data[idx] + data[idx+1] + data[idx+2];
            avg =  parseInt(avg/3);
            data[idx]  = avg;
            data[idx+1] = avg;
            data[idx+2] = avg;
        }
    }

    ImgDataToSave({
        width,
        height,
        data
    });
}).catch((e)=>{
    console.log("错误:",e);
});

  

使用,执行  

node ./index.js   ./test.png

  

猜你喜欢

转载自www.cnblogs.com/muamaker/p/12083790.html
PNG