JS 解析 png 图片的分辨率(宽高)

73 阅读1分钟

创建一个文件

touch image-size.cjs

然后写入下面内容:

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

// PNG文件头结构:
// 前8字节:文件签名
// 第12-16字节:宽度(4字节大端)
// 第16-20字节:高度(4字节大端)
function getPNGDimensions(filePath) {
  try {
    // 读取文件前24字节
    const data = fs.readFileSync(filePath, { length: 24 });

    // 验证PNG文件签名
    const signature = data.toString('hex', 0, 8);
    if (signature !== '89504e470d0a1a0a') {
      throw new Error('不是有效的PNG文件');
    }

    // 提取宽度和高度(大端序)
    const width = data.readUInt32BE(16);
    const height = data.readUInt32BE(20);

    return { width, height };
  } catch (err) {
    console.error(`读取 ${path.basename(filePath)} 失败:`, err.message);
    return null;
  }
}

// 使用示例
const imgDir = path.join(__dirname, 'images');

fs.readdir(imgDir, (err, files) => {
  if (err) throw err;

  files.forEach(file => {
    if (path.extname(file).toLowerCase() === '.png') {
      const filePath = path.join(imgDir, file);
      const dimensions = getPNGDimensions(filePath);

      if (dimensions) {
        console.log(
          `${file.padEnd(20)} 分辨率: ${dimensions.width}x${dimensions.height}`
        );
      }
    }
  });
});

现在,运行上面代码,可以打印出文件夹 images 中所有 png 图片的分辨率。

参考链接: