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

创建一个文件

sh 复制代码
touch image-size.cjs

然后写入下面内容:

js 复制代码
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 图片的分辨率。

参考链接:

相关推荐
mCell17 小时前
GSAP ScrollTrigger 详解
前端·javascript·动效
gnip17 小时前
Node.js 子进程:child_process
前端·javascript
codingandsleeping1 天前
使用orval自动拉取swagger文档并生成ts接口
前端·javascript
白水清风1 天前
微前端学习记录(qiankun、wujie、micro-app)
前端·javascript·前端工程化
用户22152044278001 天前
new、原型和原型链浅析
前端·javascript
阿星做前端1 天前
coze源码解读: space develop 页面
前端·javascript
叫我小窝吧1 天前
Promise 的使用
前端·javascript
前端康师傅1 天前
JavaScript 作用域
前端·javascript
云枫晖1 天前
JS核心知识-事件循环
前端·javascript
eason_fan1 天前
Git 大小写敏感性问题:一次组件重命名引发的CI构建失败
前端·javascript