PS js скрипт для циклического переворачивания слоев, отображения одного за другим и сохранения каждый раз между

Надеюсь, название не звучит запутанно. Что я пытаюсь сделать с помощью сценария:

  1. Откройте слой смарт-объекта в рабочем файле.
  2. Получает имя первого слоя, делает первый слой видимым, обновляет смарт-объект.
  3. Получает имя и активный слой из группы (цвет) из основного документа.
  4. 2.Name + 3.Name и сохраняет как.png.

Пожалуйста, смотрите мою диаграмму и короткую заставку здесь: http://recordit.co/2QnBK0ZV2M

Диаграмма рабочего процесса

Спасибо за любую помощь!

#target photoshop


//This stores the currently active document to the variable mockupDoc
var mockupDoc = app.activeDocument;
 
//This stores Front.psd file's name so Photoshop can look for the active layers in the correct document.
var designDoc = app.documents.getByName("Front.psd");
 
//Gets the name of tha active layer of Front.psd
var designlayer = designDoc.activeLayer;  

// getting the name and location;
var docName = mockupDoc.name;  
if (docName.indexOf(".") != -1) {var basename = docName.match(/(.*)\.[^\.]+$/)[1]}  
else {var basename = docName};  

// getting the location, if unsaved save to desktop;  
try {var docPath = mockupDoc.path}  
catch (e) {var docPath = "~/Desktop"}; 

// jpg options, But would love to save trough my Tiny png/jpg PS plugin instead PS native 
var jpegOptions = new JPEGSaveOptions();  
jpegOptions.quality = 9;  
jpegOptions.embedColorProfile = true;  
jpegOptions.matte = MatteType.NONE;  

// Saves the Mockup File containing the Name of the active layer in Front.psd
mockupDoc.saveAs((new File(docPath+'/'+basename + ' ' + designDoc.activeLayer.name +'.jpg')),jpegOptions,true);      

Добавил мой текущий код выше. Я борюсь со следующими задачами:

  1. Как я могу проверить, какой слой активен в layerset/group "Colors" документа mockupDoc и сохранить его как переменную, чтобы использовать его в качестве имени при сохранении?

    1. Мне нужно, чтобы скрипт проходил через каждый слой Front.psd сверху вниз, например: Начните с верхнего слоя, сделайте видимым только этот слой -> сохраните этот документ -> вернитесь в mockup.psd -> сохраните этот файл как jpg и png -> вернуться к Front.psd и перейти на следующий слой, чтобы повторить эти шаги (видимый / сохранить / предыдущий документ / сохранить png jpg/ и т. д.)? Как сценарий узнает, когда последний слой был обработан, и остановит сценарий?

    2. Прямо сейчас скрипт сохраняет файлы в корневой папке mockup.psd. Можно ли иметь там папки по цветам (т.е. красным, желтым...) и проверить файл, который я хочу сохранить, для переменной "цвета", которую я сохранил ранее, и сохранить в желтой папке, если переменная желтая?

Надеюсь, это не звучит странно, мой английский отстой;)

Спасибо всем за вашу помощь.

2 ответа

Решение

Спасибо @Mr Mystery Guest

Тем временем я решил большинство задач и добавил свой код ниже. Может быть, некоторые другие пользователи найдут его полезными или найдут лучшие решения.

//================================= OPTIONS ================================= 

// jpg options.
  var jpegOptions = new JPEGSaveOptions();  
  jpegOptions.quality = 9;  
  jpegOptions.embedColorProfile = true;  
  jpegOptions.matte = MatteType.NONE;  

// PNG options.
    pngOptions = new PNGSaveOptions()
    pngOptions.compression = 0
    pngOptions.interlaced = false


//================================= VARIABLES ================================= 


// Variables for the "Paste in Place" function
  cTID = function(s) { return app.charIDToTypeID(s); };
  sTID = function(s) { return app.stringIDToTypeID(s); };

// Checks which one is the Mockup.psd file (as my names differ but allways contain "Mockup")
  var docs = app.documents;
  for(var i = docs.length - 1; i >= 0; i--){
    if(docs[i].name.indexOf('Mockup') > 0){
      var mockupDoc = docs[i];
    }
  }


// Getting the name and location of Mockup.psd and remove "Mockup" from the name/string.
  var mockupDocName = mockupDoc.name.replace(/Mockup /i,'');  
  if (mockupDocName.indexOf(".") != -1) {var basename = mockupDocName.match(/(.*)\.[^\.]+$/)[1]}  
  else {var basename = mockupDocName};  

  
// Getting the location of Mockup.psd;  
  var mockupDocPath = mockupDoc.path


// Setting variable for layerset "GTO Background" 
  var gtoBG = mockupDoc.layerSets.getByName("GTO Background");


// This stores Front.psd file's name so Photoshop can look for the active layers in the correct document.
  var designDoc = app.documents.getByName("Designs Front.psd");
  var currentLayer = designDoc.activeLayer;


// create a variable that holds the number of layers in the psd
var numOfLayers = designDoc.layers.length;

// temp string to hold all layer names
//var str = ""

    // get the name of each layer
    //var layerName = designDoc.layers[i].name;

    // add the layer name to a string
    //str += layerName + "\n";


function resetDesignDoc (){
// Sets "FRONT.psd" aka designDoc as active document.
  app.activeDocument = designDoc;

// loop over each layer - from the background to the top
for (var i = numOfLayers -1; i >= 0  ; i--)
// for the top to the bottom use: for (var i = 0; i < numOfLayers; i++)
{
    designDoc.layers[i].visible = false; // Hide all Layers
    designDoc.activeLayer = designDoc.layers[0]; // Selects the top layer
    designDoc.activeLayer.visible = true; // Make Top Layer Visible

} 
};


//================================= MAIN ================================= 
// Reset "Front.psd" aka designDoc 
resetDesignDoc()

var create = true;


while (create) {
CreateMockup();      // Create Item
  gotoNextLayer();      // Select Next Layer
  selectNEXT()
  if(designDoc.activeLayer.name.indexOf("END") >= 0){
           //alert('All Designs Applied')
            var create = false;

    } 

}




// Create Mockup
  function CreateMockup() {

 // Sets "Mockup.psd" aka mockupDoc as active document.
  app.activeDocument = mockupDoc;

// Toggles layerset "GTO BBACKGROUND" to visible for .jpg version export.
  gtoBG.visible = true;

// Sets "FRONT.psd" aka designDoc as active document.
  app.activeDocument = designDoc;

// Saves "Front.psd" to original destination and updates embeded content (smart object) in "Mockup.psd" aka mockupDoc
  var designDocPath = designDoc.path;
  var Name = designDoc.name.replace(/\.[^\.]+$/, ''); 
  designDoc.saveAs(File(designDocPath + "/" + Name + ".psd"));

// Sets "Mockup.psd" aka mockupDoc as active document.
  app.activeDocument = mockupDoc;

// Checks if current Design is a "FLEX" print or not.
if(designDoc.activeLayer.name.toLowerCase().indexOf("flex") >= 0){
    //Hides Texture Overlays
        Selecttexures();
       }


// Creates a Sharpness Layer for the jpg version.
  createSharpnessLayer ();

// Saves the composited image from Mockup.psd containing Filename minus "Mockup", Name of the visible layer "Colors" layerset and the Name of the active layer in Front.psd
  mockupDoc.saveAs((new File(mockupDocPath + "/_Files Export/with GTO Background" +'/' + basename + ' ' + designDoc.activeLayer.name +'.jpg')),jpegOptions,true);      

// Remove OLD Sharpness Layer
  mockupDoc.layers.getByName('Sharpness').remove(); 

// Toggles layerset "GTO BBACKGROUND" to hidden for .png version export.
  gtoBG.visible = false;

// Creates a Sharpness Layer for the png version.
  createSharpnessLayer ();

// Saves the composited image from Mockup.psd containing Filename minus "Mockup", Name of the visible layer "Colors" layerset and the Name of the active layer in Front.psd
  mockupDoc.saveAs((new File(mockupDocPath + "/_Files Export/png" +'/' + basename + ' ' + designDoc.activeLayer.name +'.png')),pngOptions,true);     

// Remove OLD Sharpness Layer
  mockupDoc.layers.getByName('Sharpness').remove(); 


} //END Create Items function



  // Select Next Layer

function gotoNextLayer() {

// Sets "FRONT.psd" aka designDoc as active document.
  app.activeDocument = designDoc;


  };

  // Selects Next Layer in Front.psd aka designDoc and makes only this one visible.
  function selectNEXT(enabled, withDialog) {
    if (enabled != undefined && !enabled)
      return;
    var dialogMode = (withDialog ? DialogModes.ALL : DialogModes.NO);
    var desc1 = new ActionDescriptor();
    var ref1 = new ActionReference();
    ref1.putEnumerated(cTID('Lyr '), cTID('Ordn'), cTID('Bckw'));
    desc1.putReference(cTID('null'), ref1);
    desc1.putBoolean(cTID('MkVs'), false);
    executeAction(cTID('slct'), desc1, dialogMode);
  };


//================================= HELPERS ================================= 

// "Paste in Place" function.
function pasteInPlace(enabled, withDialog) {
    if (enabled != undefined && !enabled)
    return;
    var dialogMode = (withDialog ? DialogModes.ALL : DialogModes.NO);
    var desc1 = new ActionDescriptor();
    desc1.putBoolean(sTID("inPlace"), true);
    desc1.putEnumerated(cTID('AntA'), cTID('Annt'), cTID('Anno'));
    executeAction(cTID('past'), desc1, dialogMode);
};

 
// Create "Sharpness" Layer.
function createSharpnessLayer () { 
  mockupDoc.selection.selectAll();  
  mockupDoc.selection.copy(true); 
  pasteInPlace();
  mockupDoc.activeLayer.name = "Sharpness" 
  mockupDoc.activeLayer.move( mockupDoc, ElementPlacement.PLACEATBEGINNING );
  mockupDoc.activeLayer.applyHighPass(0.5)
  mockupDoc.activeLayer.blendMode  = BlendMode.LINEARLIGHT;
  mockupDoc.activeLayer.opacity = 50; 
};  

// Select all print texture overlays in "Mockuo.psd" aka mockupDoc
function Selecttexures() {
  // Select
  function step1(enabled, withDialog) {
    if (enabled != undefined && !enabled)
      return;
    var dialogMode = (withDialog ? DialogModes.ALL : DialogModes.NO);
    var desc1 = new ActionDescriptor();
    var ref1 = new ActionReference();
    ref1.putName(cTID('Lyr '), "LIGHT FABRIC TEXTURE");
    desc1.putReference(cTID('null'), ref1);
    desc1.putBoolean(cTID('MkVs'), false);
    var list1 = new ActionList();
    list1.putInteger(43);
    desc1.putList(cTID('LyrI'), list1);
    executeAction(cTID('slct'), desc1, dialogMode);
  };

  // Select Linked Layers
  function step2(enabled, withDialog) {
    if (enabled != undefined && !enabled)
      return;
    var dialogMode = (withDialog ? DialogModes.ALL : DialogModes.NO);
    var desc1 = new ActionDescriptor();
    var ref1 = new ActionReference();
    ref1.putEnumerated(cTID('Lyr '), cTID('Ordn'), cTID('Trgt'));
    desc1.putReference(cTID('null'), ref1);
    executeAction(sTID('selectLinkedLayers'), desc1, dialogMode);
  };

  // Hide
  function step3(enabled, withDialog) {
    if (enabled != undefined && !enabled)
      return;
    var dialogMode = (withDialog ? DialogModes.ALL : DialogModes.NO);
    var desc1 = new ActionDescriptor();
    var list1 = new ActionList();
    var ref1 = new ActionReference();
    ref1.putEnumerated(cTID('Lyr '), cTID('Ordn'), cTID('Trgt'));
    list1.putReference(ref1);
    desc1.putList(cTID('null'), list1);
    executeAction(cTID('Hd  '), desc1, dialogMode);
  };
  step1();      // Select
  step2();      // Select Linked Layers
  step3();      // Hide
};

Добро пожаловать в стек переполнения. Обычно мы просим посмотреть, какой код вы написали - даже если он не работает, просто добавьте комментарии, чтобы объяснить, что вы пытаетесь сделать. Сломанный код лучше, чем ничего, когда задаешь вопросы. Но также помните, что SO не является сервисом написания скриптов.

Зацикливание на слоях прямо вперед - пока избегайте групп - это более продвинутое. Посмотрите вокруг, и вы должны найти код, чтобы сохранить pngs.

Это поможет вам начать.

 // Call the open document the source document
 // It's easier than having to type app.activeDocument each time :)
var srcDoc = app.activeDocument;

// create a variable that holds the number of layers in the psd
var numOfLayers = srcDoc.layers.length;

// temp string to hold all layer names
var str = ""

// loop over each layer - from the background to the top
for (var i = numOfLayers -1; i >= 0  ; i--)
// for the top to the bottom use: for (var i = 0; i < numOfLayers; i++)
{
    // get the name of each layer
    var layerName = srcDoc.layers[i].name;

    // add the layer name to a string
    str += layerName + "\n";

    // set the visiblity of each layer to true (on)
    srcDoc.layers[i].visible = true;
}

// display the layer names
alert(str);



function save_as_png(myFilePath)
{
    var f = myFilePath + ".png";

    // save out the image
    var pngFile = new File(f);
    pngSaveOptions = new PNGSaveOptions();
    pngSaveOptions.embedColorProfile = true;
    pngSaveOptions.formatOptions = FormatOptions.STANDARDBASELINE;
    pngSaveOptions.matte = MatteType.NONE; pngSaveOptions.quality = 1;

    activeDocument.saveAs(pngFile, pngSaveOptions, false, Extension.LOWERCASE);
}
Другие вопросы по тегам