Fixing the bug in script CS6 version 13 by adding a layer only to the final PSD file

I've developed a code that copies images from one folder to another, matching them with their respective PSD file names. Each image with the same name is pasted as a new layer into the corresponding PSD with the same name. The condition checking if names are matched is:

if(fileListString.search(workingDocName) !== -1)

Everything was working fine until I added a condition to prevent adding images to the wrong PSDs in the previous if statement:

globals.markupFileNotFound = false; 

And later if the condition is false:

else {globals.markupFileNotFound = true;}

Previously, there was a bug which ran the script and added the last copy of a matched image from the source folder (markup locations) to all remaining PSDs in the target folder (working locations). For example, we have 001.PSD, 002.PSD, 003.PSD and 001.JPG, 002.JPG. Without the additional new condition, 003.PSD would get a copy of the image from 002.JPG, and any next PSD file would get it too.

With the new condition, only 002.PSD gets the image 002.JPG, but the previous 001.PSD does not, even when it has 001.JPG respectively. And the needed conditions worked:

if(fileListString.search(workingDocName) !== -1) = true
globals.markupFileNotFound = false;

So the code below should work, but it's not:

//Paste the markups onto the working document
if(globals.markupFileNotFound == false) {
   //Create the blank layer
   var blankLayer = openDoc.artLayers.add();
   //Rename the layer to blank Layer
   blankLayer.name = "markups";
   //paste the markups onto the markups layer
   workingDoc.paste();
                        }

As far as I know, this code is supposed to work in newer versions of Photoshop CC.

[Link to folder structure]

#target photoshop

globals = {};
main();

function main() {
    //Create a dialog box to get the details of where the markups and the working are stored
    var dialogPrefs = "dialog{statictext:StaticText{bounds:[10,10,240,27], text:'Set the folder location of the markups'}, " + 
                    "markupsButton:Button{bounds:[10,80,190,101], text:'Markups location'}, " +
                    "statictext:StaticText{bounds:[130,10,390,27], text:'Set the folder location of the working files'}," +
                    "workingButton:Button{bounds:[205,80,390,101], text:'Working location'}, " +
                    "transferButton:Button{bounds:[205,120,390,141], text:'Transfer markups'}, " +
                    "cancelButton:Button{bounds:[205,160,390,181], text:'Cancel'}};"

    var windowFileLocation = new Window(dialogPrefs, "Set file locations");

    //This is the markup window button
        windowFileLocation.markupsButton.onClick = function() {
            globals.markupFolder = Folder.selectDialog("Select markup location");
        }
        //Store the location of the markup files
    //This is the working window button
    windowFileLocation.workingButton.onClick = function() {
        globals.workingFolder = Folder.selectDialog("Select working folder location");

    }
        //Store the location of the markup files

    //This is the transfer button
    windowFileLocation.transferButton.onClick = function() {
        //Compare both folders to find the files with the same names and transfer markups
        //Check both locations to make sure that they are valid
        if (globals.markupFolder === null){
            alert("You have not selected the markups folder. Please select and try again");
        } else if (globals.workingFolder === null){
            alert("You have not selected the working folder. Please select and try again");
        } else {
            //Define an empty array to store the file names in
            var workingFileNameArray = [];
            //Get a list of all the files in the working folder
            var fileList = globals.workingFolder.getFiles();
            for(var a = 0; a < fileList.length; a++) {
                //check to see if the fileList item is a file or folder
                if(fileList[a] instanceof File) {
                    //Converting filename to a string
                    var fileListString = fileList[a].toString();
                    if(fileListString.match(/.(jpg|tif|psd|bmp|gif|png|ico)$/)) {
                        workingFileNameArray[a] = fileList[a];
                        //open the file in photoshop
                        var openDoc = open(workingFileNameArray[a]);
                        //Make a variable containing the active document
                        var workingDoc = app.activeDocument;
                        //get the name of the file and cut the extension
                        var workingDocName = ((workingDoc.name).toString()).slice(0, -4);
                        //getting the color profile of the working file
                        var targetProfile = workingDoc.colorProfileName;

                        //Start working markups
                        searchMarkups(workingDocName, targetProfile);

                        //Paste the markups onto the working document
                        if(globals.markupFileNotFound == false) {
                            //Create the blank layer
                            var blankLayer = openDoc.artLayers.add();
                            //Rename the layer to blank Layer
                            blankLayer.name = "markups";
                            //paste the markups onto the markups layer
                            workingDoc.paste();
                        }
                        //Save document
                        workingDoc.save();
                        //Close the document
                        workingDoc.close();
                    }
                }
            }
        alert("All markups have been transferred");
        windowFileLocation.close();
        }
    }

    //Cancel button
    windowFileLocation.show();
}

function searchMarkups(workingDocName, targetProfile) {
    //This is a function that will find the markup files that match the working file

    //Define an empty array to store the file names in
    var workingFileNameArray = [];
    //Define an empty array to store the file names in
    var fileList = globals.markupFolder.getFiles();
    for(var a = 0; a < fileList.length; a++){
        //check to see if the fileList item is a file or folder
        if(fileList[a] instanceof File) {
            //Converting filename to a string
            var fileListString = fileList[a].toString();
            if(fileListString.match(/.(jpg|tif|psd|bmp|gif|png|ico)$/)) {
                //Check the name of the open working file against all of the files in the markups folder and find one that matches
                if(fileListString.search(workingDocName) !== -1){
                    //open that file
                    var openDoc = open(fileList[a]);
                    //Convert the markup file to match the profile on the working
                    openDoc.convertProfile(targetProfile, Intent.RELATIVECOLORIMETRIC, true, true);
                    //Select the whole canvas
                    openDoc.selection.selectAll();
                    //Add a new blank layer to the file
                    var blankLayer = openDoc.artLayers.add();
                    //Rename the layer to blank Layer
                    blankLayer.name = "blankLayer";
                    //copy merge
                    openDoc.selection.copy(true);
                    //Remove the blank layer
                    openDoc.layers.getByName("blankLayer").remove();
                    globals.markupFileNotFound = false;
                    //close the document
                    openDoc.close(SaveOptions.DONOTSAVECHANGES);
                } else {
                    globals.markupFileNotFound = true;
                }
            }
        }
    }

}

Thanks in advance. Additional credits to code author jamesmcdonald3d.com

Answer №1

Give this code a shot and let me know how it fares. It seems that using .toString() on a file will provide you with the full path, so be cautious if your folder names share similarities with your file names. I believe Photoshop's open() function may require a path instead of just a reference to a file...

#target photoshop

globals = {};
main();

function main() {
    //Creating a dialog box for setting the markup and working folders
    var dialogPrefs = "dialog{statictext:StaticText{bounds:[10,10,240,27], text:'Set the folder location of the markups'}, " + 
                    "markupsButton:Button{bounds:[10,80,190,101], text:'Markups location'}, " +
                    "statictext:StaticText{bounds:[130,10,390,27], text:'Set the folder location of the working files'}," +
                    "workingButton:Button{bounds:[205,80,390,101], text:'Working location'}, " +
                    "transferButton:Button{bounds:[205,120,390,141], text:'Transfer markups'}, " +
                    "cancelButton:Button{bounds:[205,160,390,181], text:'Cancel'}};"

    var windowFileLocation = new Window(dialogPrefs, "Set file locations");

    //Markup window button functionality
        windowFileLocation.markupsButton.onClick = function() {
            globals.markupFolder = Folder.selectDialog("Select markup location");
        }
    
    //Working window button functionality
    windowFileLocation.workingButton.onClick = function() {
        globals.workingFolder = Folder.selectDialog("Select working folder location");
    }

    //Transfer button functionality
    windowFileLocation.transferButton.onClick = function() {
        //Comparing folders to transfer markups with matching names
        if (globals.markupFolder === null){
            alert("You have not selected the markups folder. Please select and try again");
        } else if (globals.workingFolder === null){
            alert("You have not selected the working folder. Please select and try again");
        } else {
            var workingFilesPaths = [];
            var workingFiles = globals.workingFolder.getFiles();
            for(var a = 0; a < workingFiles.length; a++) {
                if(workingFiles[a] instanceof File) {
                    var workingFilePath = workingFiles[a].toString();
                        if(workingFilePath.match(/.psd$/)) {
                            workingFilesPaths[a] = workingFilePath;
                            var openWorkingPSD = open(workingFiles[a]);
                            var workingPSD = app.activeDocument;
                            var workingPSDname = ((workingPSD.name).toString()).slice(0, -4);
                            var workingPSDcolorProfile = workingPSD.colorProfileName;

                            transferMatchingMarkupsToWorkingPSD(workingPSD,workingPSDname, workingPSDcolorProfile);

                        }
                    }
                }
            alert("All markups have been transferred");
            windowFileLocation.close();
        }
    }

    windowFileLocation.show();
}

function transferMatchingMarkupsToWorkingPSD(workingPSD,workingPSDname, workingPSDcolorProfile) {
    var markupFilesPaths = [];
    var markupFiles = globals.markupFolder.getFiles();
    for(var a = 0; a < markupFiles.length; a++){
        if(markupFiles[a] instanceof File) {
            var markupFilePath = markupFiles[a].toString();
            if(markupFilePath.match(/.(jpg|tif|psd|bmp|gif|png|ico)$/)) {
                if(markupFilePath.search(workingPSDname) !== -1){
                    var openMarkupFile = open(markupFiles[a]);
                    openMarkupFile.convertProfile(workingPSDcolorProfile, Intent.RELATIVECOLORIMETRIC, true, true);
                    openMarkupFile.selection.selectAll();
                    openMarkupFile.selection.copy(true);
                    activeDocument = workingPSD;
                    var workingPSDlayer = workingPSD.artLayers.add();
                    workingPSDlayer.name = "markups";
                    workingPSD.paste();
                    openMarkupFile.close(SaveOptions.DONOTSAVECHANGES);

                }
            }
        }
    }

workingPSD.save();
workingPSD.close();

}

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

Experiencing difficulties in installing opensea-js using NPM

While working on my project, I encountered an issue when trying to install opensea-js as a dependency. My Node version is v14.16.0 and NPM version is v7.7.5. Every time I run the command npm install --save opensea-js, it results in an error. I attempted c ...

Tips for adjusting the border color of a MUI Select field

https://i.stack.imgur.com/rQOdg.png This MUI select box changes color from blue to black based on selection. The challenge is to customize the text and border color to white (currently set as blue). Any suggestions on how to achieve this? ...

javascript unable to delete cookie

After conducting extensive research across various articles and links on deleting cookies using JavaScript, I have encountered an issue where the JavaScript code does not seem to be functioning as expected. The code I utilized for setting cookie values usi ...

Looking to enhance code readability using regular expressions

While I am not a programmer, I enjoy exploring and learning new things. Here is what I have: 1) My URL is structured like this: http://site.com/#!/show/me/stuff/1-12/ 2) I have a jQuery pagination script that displays the number of available pages. Each ...

Having trouble linking JavaScript files to an HTML file within a standalone Java application

Hello, I am currently working on a standalone Java application that runs on a particular port number. As part of my project, I am attempting to create a user interface using HTML which involves utilizing some external JavaScript files. In order to include ...

a guide on passing variables between Python and HTML

I am currently utilizing d3.js to create a collapsible tree. The json format I receive is transformed by a python script that performs calculations based on database values. The python script begins with the root argument for the tree. From there, I calcu ...

Easily iterate through the <li> elements using jQuery and append them to the <datalist> dynamically

My jQuery loop seems to be malfunctioning as it's not showing the values of my li elements. Instead, I'm seeing [object HTMLElement] in my input search bar. <div id="sidebar-wrapper"> <input type="text" list="searchList" class="searc ...

Attaching JSON data to AngularJS form fields

I have received some JSON data in this format: [{ "Id": 0, "Text": "Item 1", "Selected": 1 }, { "Id": 1, "Text": "Item 2", "Selected": 1 }] Additionally, there is an input element as follows: <input type="text" value="{{quest ...

After a certain period of time, the NodeJs exec() function ceases to create additional

I am in the process of developing a BLE scan module on nodeJs using Bluez. Below is the code snippet I have implemented: exec('sudo hcitool lescan --duplicates &', function (error, stdout, stderr) { }); exec('sudo hcitool lescan --dupl ...

Prevent Angular Material Autocomplete from automatically updating the input field

As part of my project, I am working on creating a country autocomplete input feature. To make the input more reusable, I am looking to turn it into a component using the ControlValueAccessor interface. The goal is to have the component accept a FormControl ...

Creating dynamic bootstrap carousels with the power of jquery and javascript

I need assistance with creating a website using only html, js, and bootstrap. The issue I am facing involves implementing multiple carousels dynamically onload. Below is an example of the girls_ethnic data set. Similarly, I have boys_shirts, boys_pants, ...

Transferring information within React components

Looking for some assistance with the code below. I'm facing an issue where the data is not being submitted along with the form, even though the correct values are displayed in the form. I have included a user query to fetch data from another object an ...

Is there a way to attach an event for multiple arithmetic operations to a checkbox?

My form includes 4 checkboxes for different mathematical operations. <form action="" method="POST"> Select number of questions: <input type="number" name="que" value="que"> <br> <br> Select number of series: <select name="sel ...

Can I safely refresh the browser during integration test specifications?

We currently have a set of Protractor and Jasmine specs for our AngularJS project. Is it acceptable to use the following code snippet to clean up things between specs: afterAll(function(){ browser.restart(); } Your insights on this matter would be gre ...

Unable to navigate using single-page navigation due to JavaScript malfunction

I'm struggling with this particular code and I'm hoping for some assistance. My experience with javascript is limited, so I'm reaching out for help instead. I am trying to implement the jquery single.page.nav feature that enables navigation ...

Use Google Maps to plan your route and find out the distance in kilometers as well as the

Feeling a bit overwhelmed with the project I'm working on, but hoping for some guidance. We're aiming to create a form where users input a starting point and an ending point, similar to the examples on Google Maps (http://code.google.com/apis/ma ...

Error is thrown when attempting to access nested elements using GetElementsByClassName within the window.onload function

I have a funky looking table on my webpage, here's an example: <body> <table class="table table-bordered"> <thead> <tr> <th>#</th> <th>Product name</th> <th>Product ...

Display the HTML results within a div using jQuery autocomplete

My goal is to create an autocomplete search box. I have successfully filtered the results when typing in the textbox and verified it in the console as well as the HTML tab window. However, I am facing an issue with displaying the results below the textbox ...

Implement Javascript Event Listener

I'm a newcomer to the world of javascript and I’m struggling to understand why the code below isn't functioning correctly: var displayMessage = document.getElementById("notification"); displayMessage.addEventListener("click", function() { ...

The function parseArgs in the documentation sample code will throw a type error

import { parseArgs } from 'node:util' const args = [] const options = { t: { type: "string" } } const { values, positionals } = parseArgs({ args, options }) This code snippet is taken directly from the documentation example ...