Skip to main content
Tom114K
Known Participant
December 12, 2021
Question

Script for splitting multiple PSDs to defined slices

  • December 12, 2021
  • 3 replies
  • 4798 views

Hi guys,

I need to export data-driven graphics into slices. As far as I know, it is not possible to do that in Photoshop (I use CS5), so I would like to do this step-by-step.

 

My question: Is it possible to batch-split PSDs to multiple PSDs according to defined slices via script? Or, is it possible to batch-split existing JPGs to multiple JPGs (the slices are just dividing one document to two of them vertically, evenly spaced, so this approach might just be sufficient)? The process to solve my problem would be following:

 

1. Export Data Sets as Files (this would create tens of PSDs according to my data set)
2. Launch some script to split exported PSDs according to slices (out format: PSDs)

3. File > Scripts > Image Processor to convert PSDs to JPGs

 

OR

 

1. Export Data Sets as Files (this would create tens of PSDs according to my data set)

2. File > Scripts > Image Processor to convert PSDs to JPGs.
3. Launch some script to split JPGs according to predefined dimensions 

 

Thank you for your advice.

 

This topic has been closed for replies.

3 replies

Stephen Marsh
Community Expert
Community Expert
December 14, 2021

The following script can be recorded into a single step action, then the action can be used with the batch command.

 

Change the following as required to suit your desired column/rows layout (it does not use slices or guides):

 

var theX = 4;
var theY = 2;

 

https://community.adobe.com/t5/photoshop-ecosystem-discussions/slicing-a-very-image-24k-px-x-34k-px-into-smaller-crops/m-p/9366573

 

/* https://community.adobe.com/t5/photoshop-ecosystem-discussions/slicing-a-very-image-24k-px-x-34k-px-into-smaller-crops/m-p/9366573#M115021 */

// split image into x times y segments and save them as jpgs;
// 2017, use it at your own risk;
#target photoshop
if (app.documents.length > 0) {
var originalUnits = app.preferences.rulerUnits;
app.preferences.rulerUnits = Units.PIXELS;
// document;
var myDocument = app.activeDocument;
var theName= myDocument.name.match(/(.*)\.[^\.]+$/)[1];
var thePath = myDocument.path;
var theCopy = myDocument.duplicate("copy", true);
// the numbers;
var theX = 4;
var theY = 2;
var xFrac = myDocument.width/theX;
var yFrac = myDocument.height/theY;
// psd options;
psdOpts = new PhotoshopSaveOptions();
psdOpts.embedColorProfile = true;
psdOpts.alphaChannels = true;
psdOpts.layers = true;
psdOpts.spotColors = true;
// jpg options;
var jpegOptions = new JPEGSaveOptions();
jpegOptions.quality = 9;
jpegOptions.embedColorProfile = true;
jpegOptions.matte = MatteType.NONE;
// create folder;
var folderName = thePath+"/"+theName+"_"+theX+"x"+theY;
if (Folder(folderName).exists == false) {Folder(folderName).create()};
//save jpgs;
for (var n = 1; n <= theY; n++) {
for (var m = 1; m <= theX; m++) {
cropTo((m-1)*xFrac, (n-1)*yFrac, m*xFrac, n*yFrac);
var theNewName = theName+"_"+bufferNumberWithZeros(m, 3)+"_"+bufferNumberWithZeros(n, 3);
theCopy.saveAs((new File(folderName+"/"+"_"+theNewName+".jpg")),jpegOptions,true);
theCopy.activeHistoryState = theCopy.historyStates[0];
//executeAction( charIDToTypeID("undo"), undefined, DialogModes.NO );
}
};
theCopy.close(SaveOptions.DONOTSAVECHANGES);
// reset;
app.preferences.rulerUnits = originalUnits;
};
////// buffer number with zeros //////
function bufferNumberWithZeros (number, places) {
var theNumberString = String(number);
for (var o = 0; o < (places - String(number).length); o++) {
theNumberString = String("0" + theNumberString)
};
return theNumberString
};
////// crop //////
function cropTo (x1, y1, x2, y2) {
// =======================================================
    var desc7 = new ActionDescriptor();
        var desc8 = new ActionDescriptor();
        var idPxl = charIDToTypeID( "#Pxl" );
        desc8.putUnitDouble( charIDToTypeID( "Top " ), idPxl, y1 );
        desc8.putUnitDouble( charIDToTypeID( "Left" ), idPxl, x1);
        desc8.putUnitDouble( charIDToTypeID( "Btom" ), idPxl, y2 );
        desc8.putUnitDouble( charIDToTypeID( "Rght" ), idPxl, x2 );
    var idRctn = charIDToTypeID( "Rctn" );
    desc7.putObject( charIDToTypeID( "T   " ), idRctn, desc8 );
    desc7.putUnitDouble( charIDToTypeID( "Angl" ), charIDToTypeID( "#Ang" ), 0.000000 );
    desc7.putBoolean( charIDToTypeID( "Dlt " ), false );
    desc7.putEnumerated( stringIDToTypeID( "cropAspectRatioModeKey" ), stringIDToTypeID( "cropAspectRatioModeClass" ), stringIDToTypeID( "pureAspectRatio" ) );
    desc7.putBoolean( charIDToTypeID( "CnsP" ), false );
executeAction( charIDToTypeID( "Crop" ), desc7, DialogModes.NO );
};

 

Code taken from this topic:

https://community.adobe.com/t5/photoshop-ecosystem-discussions/slicing-a-very-image-24k-px-x-34k-px-into-smaller-crops/m-p/9366573

 

Different code that does the same thing:

https://www.andrewnoske.com/wiki/Adobe_Photoshop_-_Scripts_Related_to_Montaging

 

Another topic with related info using slices or guides to layers (not files):

https://community.adobe.com/t5/photoshop-ecosystem-discussions/divide-my-image-to-layers/m-p/12467039

 

Instructions for saving/installing code:

https://prepression.blogspot.com/2017/11/downloading-and-installing-adobe-scripts.html

 

Legend
December 14, 2021
quote

Another topic with related info using slices or guides to layers (not files):

https://community.adobe.com/t5/photoshop-ecosystem-discussions/divide-my-image-to-layers/m-p/12467039


By @Stephen Marsh

 

I liked this idea and later I rewrote the script for myself, just to save slices in psd. However, there is a small problem - it will not work in CS5, since the ability to get information about the slices of the document was added quite recently.

 

/**Divide my image to layers
 * https://community.adobe.com/t5/photoshop-ecosystem-discussions/divide-my-image-to-layers/m-p/12467520
 */
#target photoshop
var s2t = stringIDToTypeID,
    AR = ActionReference,
    AD = ActionDescriptor;

try {
    try {
        (r = new AR).putProperty(s2t('property'), p = s2t('layerID'));
        r.putEnumerated(s2t('layer'), s2t('ordinal'), s2t('targetEnum'));
        var id = executeActionGet(r).getInteger(p);
    }
    catch (e) { throw "No layer selected!\nOpen the document and select layer" }

    try {
        (r = new AR).putProperty(s2t('property'), p = s2t('slices'));
        r.putEnumerated(s2t('document'), s2t('ordinal'), s2t('targetEnum'));
        var slices = executeActionGet(r).getObjectValue(p).getList(p);
    }
    catch (e) { throw "This version of photoshop does not have access to slices" }

    (r = new AR).putProperty(s2t('property'), p = s2t('resolution'));
    r.putEnumerated(s2t('document'), s2t('ordinal'), s2t('targetEnum'));
    var res = executeActionGet(r).getDouble(p);

    (r = new AR).putProperty(s2t('property'), p = s2t('title'));
    r.putEnumerated(s2t('document'), s2t('ordinal'), s2t('targetEnum'));
    var nm = executeActionGet(r).getString(p).replace(/\..+$/, '');

    try {
        (r = new AR).putProperty(s2t('property'), p = s2t('fileReference'));
        r.putEnumerated(s2t('document'), s2t('ordinal'), s2t('targetEnum'));
        var pth = executeActionGet(r).getPath(p);
    }
    catch (e) { throw "File not saved!" }

    for (var i = 0; i < slices.count - 1; i++) {
        (r = new AR).putIdentifier(s2t('layer'), id);
        (d = new AD).putReference(s2t('target'), r);
        executeAction(s2t('select'), d, DialogModes.NO);

        (r = new AR).putProperty(s2t('channel'), s2t('selection'));
        (d = new AD).putReference(s2t('target'), r);
        d.putObject(s2t('to'), s2t('rectangle'),
            function (b, d) {
                for (var i = 0; i < b.count; i++)
                    d.putUnitDouble(k = (b.getKey(i)), s2t('pixelsUnit'), b.getInteger(k))
                return d;
            }(slices.getObjectValue(i).getObjectValue(s2t('bounds')), new AD)
        );
        executeAction(s2t('set'), d, DialogModes.NO);

        try {
            (d = new AD).putString(s2t("copyHint"), "pixels");
            executeAction(s2t("copyEvent"), d, DialogModes.NO);

            (d = new AD).putClass(s2t("mode"), s2t("RGBColorMode"));
            d.putUnitDouble(s2t("width"), s2t("distanceUnit"), 1 * 72 / res);
            d.putUnitDouble(s2t("height"), s2t("distanceUnit"), 1 * 72 / res);
            d.putUnitDouble(s2t("resolution"), s2t("densityUnit"), res);
            d.putEnumerated(s2t("fill"), s2t("fill"), s2t("white"));
            d.putInteger(s2t("depth"), 8);
            d.putString(s2t("profile"), "sRGB IEC61966-2.1");
            (d1 = new AD).putObject(s2t("new"), s2t("document"), d);
            executeAction(s2t("make"), d1, DialogModes.NO);

            (d = new AD).putEnumerated(s2t("antiAlias"), s2t("antiAliasType"), s2t("antiAliasNone"));
            d.putClass(s2t("as"), s2t("pixel"));
            executeAction(s2t("paste"), d, DialogModes.NO);

            executeAction(s2t("revealAll"), new AD, DialogModes.NO);
            executeAction(s2t("flattenImage"), undefined, DialogModes.NO);

            (d = new AD).putObject(s2t("as"), s2t("photoshop35Format"), new AD);
            d.putPath(s2t("in"), File(pth.path + '/' + nm + ' ' + ('0' + i).slice(-2) + '.psd'));
            d.putEnumerated(s2t("saveStage"), s2t("saveStageType"), s2t("saveBegin"));
            executeAction(s2t("save"), d, DialogModes.NO);

            executeAction(s2t("close"), new AD, DialogModes.NO);

            (r = new AR).putProperty(s2t('channel'), s2t('selection'));
            (d = new AD).putReference(s2t('null'), r);
            d.putEnumerated(s2t('to'), s2t('ordinal'), s2t('none'));
            executeAction(s2t('set'), d, DialogModes.NO);
        }
        catch (e) { throw e + "\nScript cannot create layer from empty space!\nMake sure that current layer contains pixels in all slices." }
    }
} catch (e) { alert(e) }

 

Stephen Marsh
Community Expert
Community Expert
December 12, 2021

Slices would appear to be unnecessary as this is just a case of two crops via canvas size adjustment.

Tom114K
Tom114KAuthor
Known Participant
December 12, 2021

This is just an example. The real situation is much more complex.

Stephen Marsh
Community Expert
Community Expert
December 12, 2021

Ah, of course, life is never simple.

 

Kukurykus posted a great link. Can I also presume that you don't know how to script Photoshop yourself?

 

EDIT: I presume that the slices are created in the parent PSD before you create the variable driven PSD child files? So when you open each file generated by the variable output it contains the slice info? If so, using the Export > Save for Web (Legacy) option can be recorded into an action for batching and it will automatically create output files from slices in say JPEG or PNG formats (do you really need PSD as output format from slices?).

 

https://helpx.adobe.com/photoshop/using/slicing-web-pages.html

 

Kukurykus
Legend
December 12, 2021