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 图片的分辨率。

参考链接:

相关推荐
灵感__idea7 小时前
Hello 算法:“走一步看一步”的智慧
前端·javascript·算法
Mh9 小时前
我决定写一个 3D 地球仪来记录下我要去的地方
前端·javascript·动效
. . . . .10 小时前
ref、useRef 和 forwardRef
前端·javascript·react.js
柚子81611 小时前
break跳出语句块的神奇技巧
前端·javascript
ejinxian12 小时前
Rust GUI框架Azul与Electron、WebView2
前端·javascript·electron
代码不加糖14 小时前
0基础搭建前后端分离项目:实现菜单与界面左右布局
java·前端·javascript·mysql·elementui·mybatis
zhensherlock14 小时前
Protocol Launcher 系列:Tally 快速计数器的深度集成
前端·javascript·typescript·node.js·自动化·github·js
AC赳赳老秦14 小时前
OpenClaw权限管理实操:团队共享Agent,设置操作权限,保障数据安全
服务器·开发语言·前端·javascript·excel·deepseek·openclaw
光影少年14 小时前
Polyline 组件如何绘制渐变区域?
前端·javascript·掘金·金石计划
普通网友14 小时前
JavaScript:ESLint+Prettier 规范代码格式
开发语言·javascript·ecmascript