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

参考链接:

相关推荐
FRing031 小时前
vue2干货总结12(loading效果、全局前置导航守卫、搜索历史管理)
开发语言·前端·javascript·vue.js·vue2
YIAN1 小时前
我踩完 DeepAgents 记忆模块的坑,才搞懂长期记忆和摘要不是一回事
前端·javascript·agent
YIAN2 小时前
用 Deep Agents 复现一个深度调研助手:从主 Agent、子 Agent 到 Skill
javascript·agent
map_3d_vis3 小时前
百度地图 JSAPI 4.0 是什么:版本说明与能力概览
前端·javascript·webgl·地图·百度地图
泯泷6 小时前
第一章:Lit简介 - 现代Web组件标准
前端·javascript·web components
kyriewen8 小时前
我让用户白等两秒,只为一个 16MB 的中文字体
前端·javascript·程序员
泯泷11 小时前
第二章:你的第一个Lit组件 - 从零到"Hello, World"
前端·javascript·web components
多加点辣也没关系12 小时前
JavaScript|第42章:安全与最佳实践
开发语言·javascript·安全
泯泷12 小时前
第三章:lit-html的威力 - 精通声明式模板
前端·javascript·web components
bai27313 小时前
npm 在 cmd 里能跑,Node 的 spawn 一调就 EINVAL:Windows 上 .cmd 的六种调法实测
javascript·后端