You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Photoshop脚本中实现运行时功能选择?求相关示例

Photoshop脚本添加运行时操作选择功能的实现方案

在Photoshop的JSX脚本中,无需依赖HTML,直接用内置的UI组件就能创建运行时选择弹窗。以下是完整的实现代码,包含你需要的Resize、转换为sRGB、移除背景三个操作选项:

// 检查是否有打开的文档
if (app.documents.length === 0) {
    alert("请先打开一张图片!");
    exit();
}

// 创建选择对话框
var dlg = new Window('dialog', '选择要执行的操作');
dlg.alignChildren = 'left';

// 添加单选按钮组
var radioGroup = dlg.add('group');
radioGroup.orientation = 'column';

var resizeBtn = radioGroup.add('radiobutton', undefined, 'Resize(调整尺寸)');
resizeBtn.value = true; // 默认选中第一个选项
var srgbBtn = radioGroup.add('radiobutton', undefined, '转换为sRGB颜色空间');
var removeBgBtn = radioGroup.add('radiobutton', undefined, '移除背景');

// 添加按钮组
var btnGroup = dlg.add('group');
btnGroup.alignment = 'center';
var okBtn = btnGroup.add('button', undefined, '确定');
var cancelBtn = btnGroup.add('button', undefined, '取消');

// 确定按钮点击事件
okBtn.onClick = function() {
    var activeDoc = app.activeDocument;
    try {
        if (resizeBtn.value) {
            // 调整尺寸操作:这里设置为宽1920px,按比例缩放高度
            var targetWidth = 1920;
            var scaleRatio = targetWidth / activeDoc.width.as('px');
            activeDoc.resizeImage(UnitValue(targetWidth, 'px'), UnitValue(activeDoc.height.as('px') * scaleRatio, 'px'));
            alert("尺寸调整完成!");
        } else if (srgbBtn.value) {
            // 转换为sRGB操作
            var srgbProfile = app.colorSettings.getRGBProfileByName('sRGB IEC61966-2.1');
            activeDoc.convertProfile(srgbProfile, Intent.RELATIVECOLORIMETRIC, true, true);
            alert("已转换为sRGB颜色空间!");
        } else if (removeBgBtn.value) {
            // 移除背景操作(PS CC 2020及以上版本支持)
            activeDoc.selection.deselect();
            activeDoc.backgroundLayer.removeBackground();
            alert("背景移除完成!");
        }
        dlg.close();
    } catch(e) {
        alert("操作失败:" + e.message);
        dlg.close();
    }
};

// 取消按钮点击事件
cancelBtn.onClick = function() {
    dlg.close();
};

// 显示对话框
dlg.show();

关键部分说明

  • 文档检查:脚本开头先判断是否有打开的图片,避免无文档时执行操作报错。
  • 对话框UI:用Window('dialog')创建原生弹窗,单选按钮组让用户明确选择操作类型。
  • 操作逻辑:
    • Resize:按目标宽度等比例缩放图片,你可以修改targetWidth的值调整需求。
    • 转换sRGB:调用PS的convertProfile方法,指定sRGB配置文件完成转换。
    • 移除背景:使用PS内置的removeBackground()方法,需确保你的PS版本在CC 2020及以上。
  • 错误处理:用try-catch捕获操作中的异常,避免脚本崩溃并给出提示。

使用方法

  1. 打开Photoshop,新建一个脚本文件(文件>脚本>新建脚本)。
  2. 将上述代码粘贴进去,保存为.jsx格式。
  3. 运行脚本(文件>脚本>浏览,选择保存的jsx文件),即可看到选择弹窗。

内容的提问来源于stack exchange,提问作者Polle

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.05 21:40:25