Copy Alpha Channels

JavaScript for Adobe Photoshop

The script copies the alpha channels from images in one folder to matching images in another folder. The script also serves as a template for creating additional scripts that perform other tasks, easily accomplished by altering the 'processDoc()' function.

  • Open source
  • Copy channels from one set of images to another
  • Option to match names exactly or if name contains the other
  • Adapt source code to create other scripts
Copy Alpha Channels screen
Download
Copy Alpha Channels

Instructions for use

The interface has three sections: Source images, Target images, and Match file names, ignoring extension. Set desired options then click the OK button to begin. A progress bar is displayed as images are processed.

Section 1: Source images

Folder — select a folder of images with alpha channels to copy.

Section 2: Target images

Folder — select a folder of images to which alpha channels will be copied, if a file matching the name (based on options below) is found in the source images folder.

Section 3: Match file names, ignoring extension

Exact — the source and target base name (file name without extension) match exactly.

Contains source name — the target image base name contains the source image base name.

Contains target name — the source image base name contains the target image base name.

Source code

(download button below)

/*

Copy Alpha Channels
Copyright 2019 William Campbell
All Rights Reserved
https://www.marspremedia.com/contact

Permission to use, copy, modify, and/or distribute this software
for any purpose with or without fee is hereby granted.

THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.

*/

#target photoshop

(function () {

    const displayDialogs = app.displayDialogs;
    const rulerUnits = app.preferences.rulerUnits;

    var btnCancel;
    var btnFolderSource;
    var btnFolderTarget;
    var btnOk;
    var doneMessage = "";
    var filesSource = [];
    var filesTarget = [];
    var folderSource;
    var folderTarget;
    var g; // group
    var p; // panel
    var rbMatchExact;
    var rbMatchSource;
    var rbMatchTarget;
    var txtFolderSource;
    var txtFolderTarget;
    var w; // window

    // SETUP

    app.displayDialogs = DialogModes.NO;
    app.preferences.rulerUnits = Units.PIXELS;

    // CREATE USER INTERFACE

    w = new Window("dialog", "Copy Alpha Channels");
    w.alignChildren = "fill";

    // Panel 'Source images'
    p = w.add("panel", undefined, "Source images");
    g = p.add("group");
    btnFolderSource = g.add("button", undefined, "Folder...");
    txtFolderSource = g.add("statictext", undefined, undefined, {truncate: "middle"});
    txtFolderSource.preferredSize = [336, -1];

    // Panel 'Target images'
    p = w.add("panel", undefined, "Target images");
    g = p.add("group");
    btnFolderTarget = g.add("button", undefined, "Folder...");
    txtFolderTarget = g.add("statictext", undefined, undefined, {truncate: "middle"});
    txtFolderTarget.preferredSize = [336, -1];

    // Panel 'Match file names, ignoring extension'
    p = w.add("panel", undefined, "Match file names, ignoring extension");
    p.alignChildren = "left";
    g = p.add("group");
    g.orientation = "row";
    rbMatchExact = g.add("radiobutton", undefined, "Exact");
    rbMatchExact.value = true;
    rbMatchSource = g.add("radiobutton", undefined, "Contains source name");
    rbMatchTarget = g.add("radiobutton", undefined, "Contains target name");

    // Action Buttons
    g = w.add("group");
    g.alignment = "center";
    btnOk = g.add("button", undefined, "OK");
    btnCancel = g.add("button", undefined, "Cancel");

    // UI ELEMENT EVENT HANDLERS

    btnFolderSource.onClick = function () {
        var f = Folder.selectDialog("Select folder of source images");
        if (f) {
            txtFolderSource.text = Folder.decode(f.fsName);
            folderSource = f;
        }
    };

    btnFolderTarget.onClick = function () {
        var f = Folder.selectDialog("Select folder of target images");
        if (f) {
            txtFolderTarget.text = Folder.decode(f.fsName);
            folderTarget = f;
        }
    };

    btnOk.onClick = function () {
        if (!folderSource) {
            alert("Select folder of source images.");
            return;
        }
        if (!folderTarget) {
            alert("Select folder of target images.");
            return;
        }
        w.close(1); // true
    };

    btnCancel.onClick = function () {
        w.close(0); // false
    };

    // DISPLAY THE DIALOG

    if(w.show()) {
        try {
            process();
            doneMessage = "Processing complete.";
        } catch (e) {
            if (/User cancelled/.test(e.message)) {
                doneMessage = null;
            } else {
                doneMessage = "An error has occurred.\nLine " + e.line + ": " + e.message;
            }
        }

        // Restore app preferences.
        app.preferences.rulerUnits = rulerUnits;
        app.displayDialogs = displayDialogs;

        if (doneMessage) { // Didn't cancel.
            alert(doneMessage);
        }
    }

    //====================================================================
    //               END PROGRAM EXECUTION, BEGIN FUNCTIONS
    //====================================================================

    function process() {
        var baseName;
        var baseNamesSource = [];
        var docSource;
        var docTarget;
        var source;
        var target;
        var i;
        var ii;
        // Gather collection of source files.
        filesSource = folderSource.getFiles(function (f) {
            if (f instanceof File && !f.hidden) {
                return true;
            }
            return false;
        });
        // Compile array of source files names minus extension.
        for (i = 0; i < filesSource.length; i++) {
            baseNamesSource[i] = File.decode(filesSource[i].name).replace(/\.[^\.]+$/, "");
        }
        // Loop through target files.
        filesTarget = folderTarget.getFiles(function (f) {
            if (f instanceof File && !f.hidden) {
                return true;
            }
            return false;
        });
        if (filesTarget.length) {
            // BEGIN PROCESSING
            progress(filesTarget.length);
            // Loop through all files.
            for (i = 0; i < filesTarget.length; i++) {
                source = null;
                target = filesTarget[i];
                progress.message(File.decode(target.name));
                // Look for matching source file.
                // Same name minus extension.
                baseName = File.decode(target.name).replace(/\.[^\.]+$/, "");
                for (ii = 0; ii < baseNamesSource.length; ii++) {
                    if (rbMatchExact.value) {
                        // Match exact.
                        if (baseNamesSource[ii] == baseName) {
                            // Match.
                            source = filesSource[ii];
                            break;
                        }
                    } else if (rbMatchSource.value) {
                        // Match if target contains source.
                        if(baseName.indexOf(baseNamesSource[ii]) > -1) {
                            // Match.
                            source = filesSource[ii];
                            break;
                        }
                    } else {
                        // Match if source contains target.
                        if(baseNamesSource[ii].indexOf(baseName) > -1) {
                            // Match.
                            source = filesSource[ii];
                            break;
                        }
                    }
                }
                if (source) {
                    // Found match. Open images and process.
                    docSource = app.open(source);
                    docTarget = app.open(target);
                    processDoc(docSource, docTarget);
                    docSource.close(SaveOptions.DONOTSAVECHANGES);
                    docTarget.close(SaveOptions.SAVECHANGES);
                }
                progress.increment();
            }
            progress.close();
            // END PROCESSING
        }
    }

    function processDoc(docSource, docTarget) {
        var channel;
        var i;
        app.activeDocument = docSource;
        // Loop through channels looking for alpha channels.
        for (i = 0; i < docSource.channels.length; i++) {
            channel = docSource.channels[i];
            if (channel.kind == ChannelType.MASKEDAREA || channel.kind == ChannelType.SELECTEDAREA) {
                // Channel is alpha. Copy to target document.
                channel.duplicate(docTarget, ElementPlacement.PLACEATEND);
            }
        }
    }

    function progress(steps) {
        var w = new Window("palette", "Progress");
        var b;
        var t = w.add("statictext");
        t.preferredSize = [450, -1];
        if (steps) {
            b = w.add("progressbar", undefined, 0, steps);
            b.preferredSize = [450, -1];
        }
        w.add("statictext", undefined, "Press ESC to cancel");
        progress.close = function () {
            w.close();
            app.refresh();
        };
        progress.increment = function () {
            b.value++;
        };
        progress.message = function (message) {
            t.text = message;
        };
        w.show();
        app.refresh();
    }

})();
Download
Copy Alpha Channels

License details included in download

For help installing scripts, see How to Install and Use Scripts in Adobe Creative Cloud Applications.

IMPORTANT: by downloading the script you agree that the software is provided without any warranty, express or implied. USE AT YOUR OWN RISK. Always make backups of important data.