图片压缩工具 | Electron应用配合 commander 提供命令行调用功能

发布于:2025-06-25 ⋅ 阅读:(21) ⋅ 点赞:(0)

OPEN-IMAGE-TINY,一个基于 Electron + VUE3 的图片压缩工具,项目开源地址:https://github.com/0604hx/open-image-tiny

功能描述

应用程序的命令行调用功能允许用户通过终端(如Windows的CMD/PowerShell或Linux/macOS的Terminal)直接输入命令与程序交互,无需图形界面。

关于 commander

Commander 是 Node.js 最流行的命令行工具库,用于快速构建 CLI 应用程序。它提供了声明式语法、参数解析、帮助生成等特性,简化命令行开发。

示例代码:

const { program } = require('commander');

program
  .name('my-cli')
  .description('一个示例CLI工具')
  .version('1.0.0');

program
  .command('greet <name>')
  .option('-c, --capitalize', '大写输出')
  .action((name, options) => {
    let output = options.capitalize ? name.toUpperCase() : name;
    console.log(`Hello, ${output}!`);
  });

program.parse(); // 解析命令行输入

代码实现

我们在 electron 应用启动时,判断命令行参数的个数,如果超过正常启动的范围,则视为命令行方式调用。

// electron/main.js
const handleCli = require('./cli')

if(process.argv.length > (app.isPackaged?1:2)){
    (async ()=>{
        //处理命令行
        await handleCli()
        setTimeout(app.quit, 200)
    })();
}
else{
    //创建 GUI 窗口
}
// electron/cli.js
const pkg = require('../package.json')

const { Command } = require("commander")
const pc = require('picocolors')
const { splitImageVertical, convertFormat } = require('./tool')

const toInt = v=>parseInt(v)

module.exports = async()=>{
    const cli = new Command()
    cli.command("convert <file>")
        .alias("c")
        .description(`转换图片格式(支持 ${pc.green("JPG/PNG/WEBP/AVIF")}`)
        .option("-q, --quality [number]", "下载文件", toInt, 100 )
        .option("-t, --target [string]", "目标格式", "WebP")
        .option("--resize [string]", "裁剪方式,width=按宽度、height=按高度")
        .option("--resizeValue [number]", "裁剪大小/单位px", toInt)
        .option("-r, --rotate [number]", "旋转角度", toInt)
        .action(async (/**@type {String} */file, /**@type {import('./tool').ConvertConfig} */ps)=>{
            await convertFormat(file, null, ps)
        })

    cli.command("split <file>")
        .alias("s")
        .description("垂直切割图片")
        .option("-h, --height [number]", "切割高度/单位px", toInt, 1000)
        .option("-f, --fit [boolean]", "高度不足时自动填充", true)
        .option("-c, --color [string]", "填充高度", "#ffffff")
        .action(async (/**@type {String} */file, /**@type {import('./tool').SplitConfig} */ps)=>{
            await splitImageVertical(file, ps)
        })

    cli
        .name(pkg.name)
        .description(pkg.description)
        .version(pkg.version)
        .parseAsync()
        .catch(e=>console.error(`${pc.red("命令行执行出错:")}${e}`))
}