Photoshop JSX脚本如何根据JSON数据无弹窗自动替换根目录对应图片
Photoshop脚本自动替换图片的问题修正
已定位的脚本故障点
- 图片路径拼接逻辑失效:未关联脚本所在根目录,文件名拼接遗漏小数点,生成的
LONDONpng类无效路径无法被识别 - 激活图层缺失:
placedLayerReplaceContents内置动作仅作用于当前选中的活动图层,脚本定位到目标图片图层后未将其设为激活状态,替换操作无法命中目标 - 路径重复包装:替换函数接收的参数已是File对象,内部二次执行
new File()包装会生成无效路径 - 无基础校验逻辑:匹配的图片文件不存在时,脚本会直接抛错中断
可直接运行的修正版本
#include json2.js // 读取JSON配置 var obj = loadJson('text.json'); // 更新文本图层内容 var textGroup = app.activeDocument.layerSets.getByName('text'); var titleLayer = textGroup.layers[0]; var coordinateLayer = textGroup.layers[1]; titleLayer.textItem.contents = obj.title; coordinateLayer.textItem.contents = obj.ord; // 定位目标图片图层 var imageGroup = app.activeDocument.layerSets.getByName('image'); var targetImageLayer = imageGroup.layers[0]; // 将目标图层设为激活状态 targetImageLayer.apply(); // 拼接脚本根目录下的同名PNG路径 var scriptRootPath = new File($.fileName).path; var replacementImage = new File(scriptRootPath + '/' + obj.title + '.png'); // 执行替换(静默无弹窗) if (replacementImage.exists) { replaceContents(replacementImage); } // 导出JPEG成品 saveJpeg(obj.title + 'Finished'); // 工具函数定义 function loadJson(relPath) { var script = new File($.fileName); var jsonFile = new File(script.path + '/' + relPath); jsonFile.open('r'); var jsonStr = jsonFile.read(); jsonFile.close(); return JSON.parse(jsonStr); } function saveJpeg(outputName) { var currentDoc = app.activeDocument; var outputFile = new File(currentDoc.path + '/' + outputName + '.jpg'); var jpegOptions = new JPEGSaveOptions(); jpegOptions.quality = 10; currentDoc.saveAs(outputFile, jpegOptions, true); } function replaceContents(sourceFile) { var replaceActionID = stringIDToTypeID("placedLayerReplaceContents"); var actionDesc = new ActionDescriptor(); var pathKeyID = charIDToTypeID("null"); actionDesc.putPath(pathKeyID, sourceFile); var pageNumKeyID = charIDToTypeID("PgNm"); actionDesc.putInteger(pageNumKeyID, 1); // 关闭所有弹窗 executeAction(replaceActionID, actionDesc, DialogModes.NO); }
内容的提问来源于stack exchange,提问作者Ashley Taylor
相关产品推荐
相关产品推荐

