浅谈Node.js:Buffer模块

2020-06-17 06:57:41易采站长站整理
89 50 4E 47 0D 0A 1A 0A
,IHDR数据块的长度为13个字节,格式如下:

域的名称字节数说明
Width4 bytes宽度
Height4 bytes高度
Bit depth1 bytes图像深度
ColorType1 bytes颜色类型
Compression method1 bytes压缩方法
Filter method1 bytes滤波器方法
Interlace method1 bytes隔行扫描方法

开始编码,如下所示:


const fs = require('fs');
const path = require('path');

const argvs = process.argv.slice(2);
if(argvs.length<=0){
console.error('请输入图片:png.js img1 img2 ...');
process.exit(-1);
}
argvs.forEach((img,idx,arr)=>{
var stat = fs.statSync(img);
fs.open(img,'r',(err,fd)=>{
if(err) throw err;
var buff = Buffer.alloc(stat.size);
fs.read(fd,buff,0,stat.size,0,(err, bytesRead, buffer)=>{
if(err) throw err;
fs.close(fd,()=>{});
getImgDimension(buff,(err,dimension)=>{
if(err) throw err;
console.log(`${img}的尺寸为:${dimension.width}x${dimension.height}`);
});
});
});
});
function getImgDimension(buff,cb){
if((buff.toString('utf8',1,8) === 'PNGrnx1an') && (buff.toString('utf8',12,16) === 'IHDR')){
return cb(null,{
width:buff.readUInt32BE(16),
height:buff.readUInt32BE(20)
}),!0;
}else{
return cb(new Error('不是PNG图片'),{}),!1;
}
}

执行结果如下:

E:developmentdocumentnodejsdemo>node png.js 20160824083157.png 下载.png
 20160824083157.png的尺寸为:195×195
下载.png的尺寸为:720×600