Snippets

renderTom PSD Script: Cut by Guides

Created by renderTom -
// Cut by Guides.
// by Tomas Šinkūnas www.rendertom.com
//
// Script cuts image into small peaces defined by Guides
// and names them according to their grid number/letter.
// Rows are named with numbers [0-9] and columns by letters [A-Z]
// Each slice is saved as PNG file with original name + grid number&letter.
// 
// Have one layer in the file. Add bunch of Guides.
// Save file as PNG and run the script. Enjoy the rest of your day!
// 
// Use it on your own risk.

(function() {
    try {
        #target photoshop

        if (app.documents.length === 0)
            return alert("Open file first");

        var doc = app.activeDocument;
        if (doc.layers.length !== 1)
            return alert("This script can handle only one layer in file. Merge your layers and run script again.");

        var originalRulerUnits = app.preferences.rulerUnits,
            plot = plotDocument(),
            selectionCoordinates = [],
            newLayer, newDocument,
            layer = doc.layers[0];

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

        layer.isBackgroundLayer && layer.isBackgroundLayer = false;
        layer.selected = true;

        doc.selection.deselect();

        for (var i = 0, il = plot.length; i < il; i++) {
            selectionCoordinates[0] = [plot[i].x, plot[i].y];
            selectionCoordinates[1] = [plot[i].x, plot[i].y + plot[i].height];
            selectionCoordinates[2] = [plot[i].x + plot[i].width, plot[i].y + plot[i].height];
            selectionCoordinates[3] = [plot[i].x + plot[i].width, plot[i].y];

            doc.selection.select(selectionCoordinates);

            if (selectionHasPixels()) {
                newLayer = layerViaCopy();
                newLayer.name = plot[i].name;
                duplicateToNewDocument(newLayer)

                app.activeDocument.trim(TrimType.TRANSPARENT);

                savePNG(File(doc.path + "/" + getBaseName(doc) + "-" + plot[i].name + ".psd"));
                app.activeDocument.close(SaveOptions.DONOTSAVECHANGES);

                app.activeDocument = doc;
                newLayer.remove();
            }
        }

        app.preferences.rulerUnits = originalRulerUnits;

        alert("done")

        /////// HELPER FUNCTIONS ///////
        
        /**
         * Converts document Guides information to array of coordinates blocks
         * @return {[Array]} [Array of objects, containing x, y, width, height, name properties]
         */
        function plotDocument() {
            var guidesArray = getGuidesCoordinates(),
                coords = [],
                vStart, vCurrent = vMin = 0,
                hStart, hCurrent = hMin = 0,
                columnName = "";

            if (guidesArray.vertical[0] !== 0)
                guidesArray.vertical.unshift(0);

            if (guidesArray.vertical[guidesArray.vertical.length - 1] < Number(app.activeDocument.width))
                guidesArray.vertical.push(Number(app.activeDocument.width))

            if (guidesArray.horizontal[0] !== 0)
                guidesArray.horizontal.unshift(0);

            if (guidesArray.horizontal[guidesArray.horizontal.length - 1] < Number(app.activeDocument.height))
                guidesArray.horizontal.push(Number(app.activeDocument.height))

            for (var h = 1, hl = guidesArray.horizontal.length; h < hl; h++) {
                hStart = hCurrent;
                hCurrent = guidesArray.horizontal[h];
                vCurrent = guidesArray.vertical[0];
                vMin = guidesArray.vertical[0];
                columnName = "a";
                for (var v = 1, vl = guidesArray.vertical.length; v < vl; v++) {
                    vStart = vCurrent;
                    vCurrent = guidesArray.vertical[v];
                    coords.push({
                        x: vStart,
                        y: hStart,
                        width: vCurrent - vMin,
                        height: hCurrent - hMin,
                        name: h + columnName
                    });
                    vMin = vCurrent;
                    columnName = String.fromCharCode(columnName.charCodeAt(0) + 1).toString();
                }
                hMin = hCurrent;
            }

            return coords
        }

        /**
         * Creates object with vertical/horizontal arrays that contain Guides coordinates
         * @return {[Object]} []
         */
        function getGuidesCoordinates() {
            var docGuides = app.activeDocument.guides,
                verticalGuides = [],
                horizontalGuides = [];
            for (var g = 0, gl = docGuides.length; g < gl; g++) {
                if (docGuides[g].coordinate >= 0) {
                    if (docGuides[g].direction === Direction.VERTICAL && docGuides[g].coordinate <= Number(app.activeDocument.width)) {
                        verticalGuides.push(Number(docGuides[g].coordinate))
                    } else if (docGuides[g].direction === Direction.HORIZONTAL && docGuides[g].coordinate <= Number(app.activeDocument.height)) {
                        horizontalGuides.push(Number(docGuides[g].coordinate))
                    }
                }
            }

            return {
                vertical: removeDuplicatesFromArray(verticalGuides).sort(),
                horizontal: removeDuplicatesFromArray(horizontalGuides).sort()
            }
        }

        /**
         * Removes Dulpicates from array
         * @param  {[Array]} userArray [Array with values]
         * @return {[Array]}   [New array without duplicates]
         */
        function removeDuplicatesFromArray(userArray) {
            var seen = {},
                out = [],
                j = 0,
                item;
            for (var i = 0, il = userArray.length; i < il; i++) {
                item = userArray[i];
                if (seen[item] !== 1) {
                    seen[item] = 1;
                    out[j++] = item;
                }
            }
            return out;
        }

        /**
         * Checks if selection has live pixels
         * @return {[Bool]} [True if selection contains pixels]
         */
        function selectionHasPixels() {
            try {
                app.activeDocument.selection.copy();
                return true 
            } catch (e) {
                return null
            }
        }

        /**
         * Creates new layer via copy.
         * @return {[Object]} [New layer]
         */
        function layerViaCopy() {
            app.activeDocument.selection.copy();        
            app.activeDocument.artLayers.add();
            app.activeDocument.paste();

            return app.activeDocument.activeLayer;
        }

        /**
         * Duplicates selected layer to new document
         * @param  {[Object]} layer [Layer to duplicate]
         * @return {[Object]}       [Returns layer in new document]
         */
        function duplicateToNewDocument(layer) {
            var doc = app.activeDocument;
            var newDocument = app.documents.add(doc.width, doc.height, doc.resolution);
            app.activeDocument = doc;

            var newLayer = layer.duplicate(newDocument, ElementPlacement.INSIDE);
            app.activeDocument = newDocument;

            newDocument.layers[newDocument.layers.length - 1].remove();

            return newLayer;
        }

        /**
         * Saves active document as PNG file with transparency
         * @param  {[Object]} saveFile [File Object with PNG extension]
         * @return Nothing
         */
        function savePNG(saveFile) {
            var pngSaveOptions = new PNGSaveOptions();
            pngSaveOptions.compression = 9;
            pngSaveOptions.interlaced = false;
            activeDocument.saveAs(saveFile, pngSaveOptions, true, Extension.LOWERCASE);
        };

        /**
         * Gets document name without extension
         * @param  {[Object]} document [Optional. Document to whos name to get]
         * @return {[String]}          [Document name without extension]
         */
        function getBaseName(document) {
            document = document || app.activeDocument;
            return decodeURI(document.name.substring(0, document.name.lastIndexOf(".")));
        }
        
    } catch (e) {
        alert(e.toString() + "\nScript File: " + File.decode(e.fileName).replace(/^.*[\|\/]/, '') +
            "\nFunction: " + arguments.callee.name +
            "\nError on Line: " + e.line.toString())
    }
})();

Comments (0)

HTTPS SSH

You can clone a snippet to your computer for local editing. Learn more.