はじめに
以下を実現するスクリプトを作ってみたので紹介します。
「複数選択しているレイヤーに対して、周辺の余白をトリミングして個別にpngファイルとしてエクスポートする」
例えば、レイヤー1とレイヤー2とレイヤー3を選択している状態でこのスクリプトを実行すると、
それぞれのレイヤーの余白部分がトリミングされた状態で
レイヤー1.png、レイヤー2.png、レイヤー3.png が出力されます。
環境
OSバージョン : Windows 10
Adobe Photoshop バージョン : 19.1.3 20180323.r.293 2018/03/23: 1163761 x64
JSXスクリプト
trim_selection_layers.jsx
if (app.documents.length > 0) { // ドキュメントが1つ以上開かれている場合のみ実行
// 現在のドキュメント
var doc = app.activeDocument;
// 保存先フォルダの選択
var saveFolder = Folder.selectDialog("トリミングイメージの保存先フォルダの選択");
if (saveFolder != null) {
var copiedDoc = app.activeDocument.duplicate(); // ドキュメント複製
selectedLayers = GetSelectedLayers();
// 選択中の全レイヤーをいったん非表示
for (index = 0; index < selectedLayers.length; index++) {
selectedLayers[index].visible = false;
}
for (index = 0; index < selectedLayers.length; index++) {
selectedLayers[index].visible = true;
activeDocument
.trim(TrimType.TOPLEFT, true, true, true, true); // トリミング対象=左上の色
// alert(selectedLayers[index]);
// saveAsで保存
saveAsPng(doc, saveFolder, selectedLayers[index].name + ".png");
stepHistoryBack();
selectedLayers[index].visible = false;
}
copiedDoc.close(SaveOptions.DONOTSAVECHANGES);
}
}
// UNDOを実行
function stepHistoryBack() {
var desc = new ActionDescriptor();
var ref = new ActionReference();
ref.putEnumerated(charIDToTypeID("HstS"), charIDToTypeID("Ordn"), charIDToTypeID("Prvs"));
desc.putReference(charIDToTypeID("null"), ref);
executeAction(charIDToTypeID("slct"), desc, DialogModes.NO);
};
// 選択中のレイヤーを取得(https://forums.adobe.com/thread/2281117)
function GetSelectedLayers() {
var A = [];
var desc11 = new ActionDescriptor();
var ref9 = new ActionReference();
ref9.putClass(stringIDToTypeID('layerSection'));
desc11.putReference(charIDToTypeID('null'), ref9);
var ref10 = new ActionReference();
ref10.putEnumerated(charIDToTypeID('Lyr '), charIDToTypeID('Ordn'), charIDToTypeID('Trgt'));
desc11.putReference(charIDToTypeID('From'), ref10);
executeAction(charIDToTypeID('Mk '), desc11, DialogModes.NO);
var gL = activeDocument.activeLayer.layers;
for (var i = 0; i < gL.length; i++) {
A.push(gL[i]);
}
executeAction(charIDToTypeID('undo'), undefined, DialogModes.NO);
return A;
};
/**
* ドキュメントをPNG画像として保存します(別名で保存相当)。
*
* @param {Document} doc
* @param {Folder} folder
* @param {string} name
*
*/
function saveAsPng(doc, folder, name) {
// フォルダが存在しない場合作成
if (!folder.exists) {
folder.create();
}
var file = new File(folder.fsName + "/" + name);
// PNG保存のためのオプション
var options = new PNGSaveOptions();
var asCopy = true;
// 保存
doc.saveAs(file, options, asCopy, Extension.LOWERCASE);
}
```
## 参考URL
選択中のレイヤーを取得するJSXは下記URLを参考にしました。
https://forums.adobe.com/thread/2281117