Automate the process of swapping out content within multiple smart objects in Photoshop CC version 20.0.0 using batch scripting

I am working with a set of 28 *.tif image files organized as layers in a .psd file. My goal is to replace each layer with a different .tif file using a script (jsx) with a loop structure like this:

for (i=1;i<=28;i++) {
  for j in (start,end) {
     for k in (a,b,c,d,e,f) {
            file = 'chr' + $i + '_' + $j + '_' + $k;
                     }}}

Update July 2020: After some time, I managed to find a solution which involves downloading json2.js and implementing it into the code snippet below:

// Replace smart object content and save psd;
#target photoshop
#include json2.js
if (app.documents.length > 0) {
  var myDocument = app.activeDocument;
  var theName = myDocument.name.match(/(.*)\.[^\.]+$/)[1];
  var thePath = myDocument.path;

  psdOpts = new PhotoshopSaveOptions();
  psdOpts.embedColorProfile = true;
  psdOpts.alphaChannels = true;
  psdOpts.layers = true;
  psdOpts.spotColors = true;

// Lists for desired filename input 
    var ppath = "c:/here/goes/file/path/for/taking/input/file";
// (You can implement using JSON too)
       var num = [
      "2",
      "3",
      ...
      ];

...
...
  
// Main code implementation begins here:

      for (var i in num) {
        saveJPEG(thNamer);
        alert("saved Jpeg");
        myDocument.saveAs((new File("D:\\thesis-bioinformatics" + '/vol-ID/' + thNamer + "_" +".psd")),psdOpts,true);
        alert("saved PSD");

          for (var k in letter) {
            var TitleGroup = myDocument.layerSets.getByName('chr_place_plot_');
...

      }
    }
};  

Answer №1

Give This Script a Shot

This script will iterate through all layers and replace them with the .tiff file that you select

var doc = app.activeDocument;

function editContent() {

cTID = function(s) { return app.charIDToTypeID(s); };
sTID = function(s) { return app.stringIDToTypeID(s); };

function Rename() {
  // Edit Contents
  function step1(enabled, withDialog) {
    if (enabled != undefined && !enabled)
      return;
    var dialogMode = (withDialog ? DialogModes.ALL : DialogModes.NO);
    var desc1 = new ActionDescriptor();
    executeAction(sTID('placedLayerEditContents'), desc1, dialogMode);
  };

  step1();      // Edit Contents
};

Rename.main = function () {
  Rename();
};

Rename.main();

    }

function merge() {
    var fileRef = File.openDialog ('Choose File', ['*.tif;*tiff'], true);
    app.open( new File( fileRef ) );
    if(app.activeDocument.activeLayer.isBackgroundLayer ) app.activeDocument.activeLayer.name = 'From Background';    
    app.activeDocument.selection.selectAll();
    app.activeDocument.selection.copy();
    app.activeDocument.selection.deselect();


    var idMk = charIDToTypeID( "Mk  " );
    var desc8946 = new ActionDescriptor();
    var idnull = charIDToTypeID( "null" );
        var ref1324 = new ActionReference();
        var idBckL = charIDToTypeID( "BckL" );
        ref1324.putClass( idBckL );
    desc8946.putReference( idnull, ref1324 );
    var idUsng = charIDToTypeID( "Usng" );
        var ref1325 = new ActionReference();
        var idLyr = charIDToTypeID( "Lyr " );
        var idOrdn = charIDToTypeID( "Ordn" );
        var idTrgt = charIDToTypeID( "Trgt" );
        ref1325.putEnumerated( idLyr, idOrdn, idTrgt );
    desc8946.putReference( idUsng, ref1325 );
executeAction( idMk, desc8946, DialogModes.NO );



    app.activeDocument.close(SaveOptions.SAVECHANGES);
    app.activeDocument.artLayers.add();
    app.activeDocument.paste();
    app.activeDocument.flatten();
    app.activeDocument.close(SaveOptions.SAVECHANGES);
    }

for (var i=0;i<doc.layers.length;i++){ 
    doc.activeLayer=doc.layers[i];
    editContent();
    merge();
    }

Answer №2

This script takes input in JSON format to replace text or images by specifying the file path.

It searches for a specified layer group and replaces its content with the provided text or image, then saves both JPG and PSD files in an output folder.

You can access the code here.


#target photoshop
#include json2.js // json to js parser

// More details about the functionality of this script...

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Separate the divs in a template into individual templates, or alternatively, utilize ng-if to display different divs within a single template

As a newcomer to AngularJS, I am seeking advice on the most efficient way to code for the given scenario: Scenario: I have a single HTML template containing multiple divs, and I need to display only one div at a time based on specific conditions. Two app ...

When using Python's requests.json() object as a dictionary, it fails to identify its own keys when using hasattr() or checking for keys using object.keys

Summary: When accessing a dictionary or JSON object, it appears that the object does not have a certain key even though it is present when checking with hasattr call or a boolean test such as value in object.keys(). How can I access the value for that spec ...

The WebSocket connection attempt to 'ws://localhost:3000/' was unsuccessful as the connection closed before receiving a handshake response

Attempting to enhance a game created by a friend, I aimed to enable cross-browser play by transmitting keypress data between peers using WebRTC and websockets. Despite my efforts, I encountered the following error in the console: WebSocket connection to ...

Adding a subscript symbol in Vue.js: A step-by-step guide

Can you guide me on how to insert the registered trademark symbol ® after SAP in my content? { number: '02', title: 'Enhanced Automation Agents ', descriptionTwo: [ 'Achieve significant savings on infrastructur ...

Fields that have been loaded are not initialized within the supplementary function

Two functions are used to load components for a page and save them in two fields - representatives and allUsers. An additional function, subtractSets(), is then used to modify the loaded data slightly. The issue arises when these fields (representatives ...

Image is not showing up on the Carousel

I seem to have a problem with my carousel as the images are not showing up when the webpage initially loads. The issue arises in Dreamweaver where the JavaScript function only works after clicking on one of the arrow buttons. I believe that I might need to ...

The onmessage event in the websocket client seems to be malfunctioning and is not triggering

In my implementation using node.js, I have set up a websocket server and client. The handshake process between the server and client appears as follows: Request URL: ws://localhost:8015/ Request Method: GET Status Code: 101 Switching Protocols Request ...

In Next.js, the Typescript compiler does not halt when an error occurs

I am looking to incorporate Next.js with TypeScript into my project. I followed the official method of adding TypeScript to Next.js using npx create-next-app --typescript. Everything seemed fine, but when a TypeScript error occurs (e.g. const st: string = ...

Obtain the value for every span class and insert the corresponding string into the input field

I have a series of tags labeled as 'tag-label' in spans. My goal is to combine the values of these tags and insert them into an input field, separating each value with commas. To demonstrate this, I've created a JSFiddle that showcases the ...

Decoding JSON data from boto3 output

Here is the code I am using to retrieve IAM users: #!/usr/bin/env python import boto3 import json client = boto3.client('iam') response = client.list_users( ) print response Upon running the code, the followin ...

What causes my local storage to be cleared whenever I refresh the page in React with Redux?

What causes my local storage to reset to empty whenever I refresh the page? I am attempting to save data to local storage that is also passed to my redux state, but I am unable to do so. const retrieveLocalStorage = () => { const oldExpenses = JSON ...

Implementing the IF statement in jQuery

I've been trying to implement an overflow check when hovering over a div. The issue arises because I'm using jQuery for the hover function and then simple JavaScript for the overflow check in the next step. It seems that directly using an if-then ...

Firebase Authentication error code "auth/invalid-email" occurs when the email address provided is not in a valid format, triggering the message "The email address is

Currently, I am working on integrating Firebase login and registration functionality into my Angular and Ionic 4 application. Registration of user accounts and password retrieval are functioning properly as I can see the accounts in my Firebase console. Ho ...

Spin Three.js camera around central point with mouse control

I am attempting to achieve camera rotation around the central point (0, 0, 0) using mouse controls. However, when rotating 180deg to the right or left, and then attempting to rotate vertically, the vertical rotation does not occur at all. My approach inv ...

Is there a way I can appropriately display an image in a specific size box?

Check out the code snippet I wrote below: import React from 'react' function OurCourse() { return ( <div className='w-full '> <div className='w-full h-[390px]' style={{ backgroundImage:&apos ...

Toggle the visibility of a div by clicking on a label

I am working with three unique labels, each with different ids and three distinct divs also with different ids. <asp:Label ID="CA" runat="server" Font-Bold="False" Font-Names="Arial" Font-Size="10pt" style="padding-top:6px;" ForeColor="#CCCCCC" Height ...

Changing the location.hash parameter prior to the page loading

Imagine a scenario where a page contains only the following script: <script type="text/javascript"> window.location.hash = 'testing'; window.history.back(); </script> When you navigate to google.com and then load this page, you& ...

What is the reason for the JSON Structure always displaying a numeric key first?

(The Challenge of Updating JSON Structure based on User Interaction) Utilizing Angular Typescript, I dynamically create a JSON structure that reflects user interactions within certain components. Process Overview The initial default setting for the J ...

jQuery shorthand conditional statements

I currently have a jQuery function that is triggered by two separate buttons. $("#btnSearch, #btnDirectorSearch").click(function () { The construction of the HTML output within this function relies on which button was clicked. To accomplish this, I am ut ...

What is the best way to pass an SQL variable from an HTML table to a JS popup and then to a PHP variable without using jQuery?

My goal is to develop software for a job board where jobs can be added and maintenance workers can mark them as completed. I am currently facing an issue with passing the request_ID from my table to the SQL query at the bottom in deleteData(). Despite tryi ...