nodejs pixel level image processing png

Use node of the pixel image processing

Here gradation processing using a common picture as an example:

Uses pngjs of npm library, which can be png image file Buffer flow, rgba converted into a pixel value of 255, but can also be 255 pixel values ​​rgba, converted to a Buffer stream file, and then written to the file.

 

example:

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
                });
            }
        ); 
    }) 
} 


// save the data to a file 
function ImgDataToSave (imgData) { 
    the let {width, height, Data = imgData}; 
    var = newPng new new PNG ({ 
        filterType:. 4, 
        width: width, 
        height: height 
    }); 
    Data = newPng.data; 
    var fs.createWriteStream DST = ( 'Export /' + + OutDir 'PNG.'); 
    newPng.pack () pipe (DST);. 
} 

// after acquiring image gradation processing 
getImgData (pngFile). the then ((RES) => { 
    the let {width, height, Data} = RES; 
    for (the let I = 0; I <height; I ++) { 
        for (the 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);
});

  

Executes  

node ./index.js   ./test.png

  

 

Guess you like

Origin www.cnblogs.com/muamaker/p/12083790.html