Create document export preview

Anyone, especially newbies, asking for help with Photoshop Scripting and Photoshop Automation - as opposed to those contributing to discussion about an aspect of Photoshop Scripting

Moderators: Tom, Kukurykus

Ferb

Create document export preview

Post by Ferb »

Hi

I've got a script which rescale a document, traverses thru all folders export folders which are marked as PNG and saves the png in corrensponding folder strucrure and xml structure (with coordinates etc)

What i wanna do is create a sepparate document on the side where every exported png is placed in, with the coordinates which are stored in the xml

So i've got al the values. How do i put everything into place?

my script:

Code: Select all#target photoshop

var documentSizeScaling= parseInt( prompt("Verhouding in procent van uitgestuurde plaatjes", 100) ) / 100;

var quality= parseInt( prompt("Kwaliteit", 100) ) ;

 myPrs = new Window('palette', 'Batch Processing');
 myPrs.orientation = 'column';
 myPrs.alignment = 'right';
 myPrs.ProcessHead  = myPrs.add('statictext',[40,0,260,25], "Batch Processing...");
 myPrs.Process = myPrs.add("progressbar",[40,40,260,65]);
 myPrs.Label = myPrs.add('statictext', [150,75,200,120], "0%");
 myPrs.Process.value = 0;

var layerCount = 0;
var layersDone = 0;
var oldPath = null;
 myPrs.show();
 
 function ProgressBar(){
     var value = (layersDone / layerCount) * 100;
     myPrs.Label.text = Math.round(value) + " % ";
     myPrs.ProcessHead.text = "Batch Processing... [" + layersDone + "/"+ layerCount + "]";
     myPrs.Process.value = value;
 }
 



function main(){
    if(!documents.length) return;


    var doc = activeDocument;
    oldPath = activeDocument.path;

   
    calcLayerCount(doc.layerSets);

    traverseLayerSet(doc.layerSets, doc, oldPath, 0);
    createXML();
   
}

var originalRulerUnits = preferences.rulerUnits;
preferences.rulerUnits = Units.PIXELS;

var docRef = activeDocument;

var docWidth = docRef.width.value;
var docHeight = docRef.height.value;
var mySourceFilePath = activeDocument.fullName.path + "/";

//  Code to get layer index / descriptor
//

cTID = function(s) { return app.charIDToTypeID(s); };
sTID = function(s) { return app.stringIDToTypeID(s); };
function getLayerDescriptor (doc, layer) {
    var ref = new ActionReference();
    ref.putEnumerated(cTID("Lyr "), cTID("Ordn"), cTID("Trgt"));
    return executeActionGet(ref)
};

function getLayerID(doc, layer) {
  var d = getLayerDescriptor(doc, layer);
  return d.getInteger(cTID('LyrI'));
};

var stackorder = 0;
var indentStart = 2;

var str = "<?xml version=\"1.0\" encoding=\"UTF-8\" ?>\n";
str += "<xml>\n";
str += "\t<root code=\""+app.activeDocument.name.match(/([^\.]+)/)[1]+"\" type=\"images\">\n";

//start traversing
main();

function calcLayerCount(sets, newDoc){
    for(var a=0;a<sets.length;a++){               
        if(sets[a].name.indexOf('[PNG]') > -1){
           layerCount++;
        }else{       
            calcLayerCount(sets[a].layerSets);
        }
    }
}

function traverseLayerSet(sets, newDoc, path, tabs){
    ProgressBar();
    for(var a=0;a<sets.length;a++){               
        if(sets[a].name.indexOf('[PNG]') > -1){
            ProgressBar();
            activeDocument.activeLayer = sets[a];

            var filename = sets[a].name.replace('[PNG]', '').replace(' ','' );
           
            storeBounds(activeDocument, sets[a], a, tabs, (path +"/"+filename+".png" ));

            dupLayers();
            activeDocument.mergeVisibleLayers();
            activeDocument.resizeImage(activeDocument.width*documentSizeScaling, activeDocument.height*documentSizeScaling, 72, Preferences.interpolation)
            activeDocument.trim(TrimType.TRANSPARENT,true,true,true,true);           

            activeDocument.activeLayer.applyUnSharpMask(20,1,0);
           
           
           
           
            var saveFile= File(path +"/"+filename+".png" );           
            SavePNG(saveFile);
            app.activeDocument.close(SaveOptions.DONOTSAVECHANGES);
           
            layersDone++;
            var prct = Math.round(((layersDone/ layerCount )*100 ));
            //win.bar.value =  prct;
            ProgressBar();
        }else{
            ProgressBar();
            var newPath = new Folder(path+"/"+sets[a].name);
             for(var q=0;q<tabs+indentStart; q++){
                str += "\t";
            }           
            str +="<images code=\""+sets[a].name+"\">\n";
           
             if(!newPath.exesits) newPath.create();
            traverseLayerSet(sets[a].layerSets, newDoc, newPath, tabs+1);
           
            for(var q=0;q<tabs+indentStart; q++){
                str += "\t";
            }
            str +="</images>\n";
        }
    } 
}

function dupLayers() {
    var desc143 = new ActionDescriptor();
        var ref73 = new ActionReference();
        ref73.putClass( charIDToTypeID('Dcmn') );
    desc143.putReference( charIDToTypeID('null'), ref73 );
    desc143.putString( charIDToTypeID('Nm  '), activeDocument.activeLayer.name );
        var ref74 = new ActionReference();
        ref74.putEnumerated( charIDToTypeID('Lyr '), charIDToTypeID('Ordn'), charIDToTypeID('Trgt') );
    desc143.putReference( charIDToTypeID('Usng'), ref74 );
    executeAction( charIDToTypeID('Mk  '), desc143, DialogModes.NO );
};

function SavePNG(saveFile){
    var pngOpts = new ExportOptionsSaveForWeb;
    pngOpts.format = SaveDocumentType.PNG
    pngOpts.PNG8 = false;
    pngOpts.transparency = true;
    pngOpts.interlaced = false;
    pngOpts.quality = 2;
    activeDocument.exportDocument(new File(saveFile),ExportType.SAVEFORWEB,pngOpts);
}

function createXML(){
// Use this to export XML file to same directory where PSD file is located
    var mySourceFilePath = activeDocument.fullName.path + "/";
// create a reference to a file for output
    var csvFile = new File(mySourceFilePath.toString().match(/([^\.]+)/)[1] + app.activeDocument.name.match(/([^\.]+)/)[1] + ".xml");
    // open the file, write the data, then close the file
    csvFile.open('w');
    csvFile.writeln(str + "\t</root>\n</xml>");
    csvFile.close();
    preferences.rulerUnits = originalRulerUnits;
}


function storeBounds(newDoc, layer, i, tabs, fullPath) {
    var isVisible = layer.visible;
    var layerData = cLayer(newDoc, layer);


    var path = fullPath.replace(oldPath+'/', '');

    for(var q=0;q<tabs+indentStart; q++){
        str += "\t";
        }
    var name = layer.name.replace('[PNG]', '').replace(' ','');
   
    // Layer object main coordinates relative to its active pixels
    var str2 = "<image code=\"" + name
   + "\" stack=\"" + (i) // order in which layers are stacked, starting with zero for the bottom-most layer
   + "\" position=\"" + leftTop // this is the
   + "\" width=\"" + Math.round(layerData.layerWidth*documentSizeScaling)
   + "\" height=\"" + Math.round(layerData.layerHeight*documentSizeScaling) 
     + "\" path=\""+ path +"\">"
   //+ "\" transformpoint=\"" + "center" + "\">" // hard-coding 'center' as the default transformation point
   + name + ".png" + "</image>\n" // I have to put some content here otherwise sometimes tags are ignored
    //+ " />"   
    str += str2.toString();

};

///////////////////////////////////////////// XML PART

// class using a contructor
function cLayer(newDoc, layer) {

//this.layerID = Stdlib.getLayerID(doc, layer);
   this.layerID = getLayerID(newDoc, layer);
  //alert("layer ID: " + this.layerID);
   this.layerWidth = layer.bounds[2].value - layer.bounds[0].value;
      this.layerHeight = layer.bounds[3].value - layer.bounds[1].value;
 
   // these return object coordinates relative to canvas
      this.upperLeftX = layer.bounds[0].value;
      this.upperLeftY = layer.bounds[1].value;
      this.upperCenterX = this.layerWidth / 2 + layer.bounds[0].value;
      this.upperCenterY = layer.bounds[1].value;
      this.upperRightX = layer.bounds[2].value;
      this.upperRightY = layer.bounds[1].value;
      this.middleLeftX = layer.bounds[0].value;
      this.middleLeftY = this.layerHeight / 2 + layer.bounds[1].value;
      this.middleCenterX = this.layerWidth / 2 + layer.bounds[0].value;
      this.middleCenterY = this.layerHeight / 2 + layer.bounds[1].value;
      this.middleRightX = layer.bounds[2].value;
      this.middleRightY = this.layerHeight / 2 + layer.bounds[1].value;
      this.lowerLeftX = layer.bounds[0].value;
      this.lowerLeftY = layer.bounds[3].value;
      this.lowerCenterX = this.layerWidth / 2 + layer.bounds[0].value;
      this.lowerCenterY = layer.bounds[3].value;
      this.lowerRightX = layer.bounds[2].value;
      this.lowerRightY = layer.bounds[3].value;
    
     // I'm adding these for easier editing of flash symbol transformation point (outputs a 'x, y' format)
     // because I like to assign shortcut keys that use the numeric pad keyboard, like such:
     //      7   8   9
     //      4   5   6
     //      1   2   3
     //
     

     this.leftBottom = Math.round(this.lowerLeftX*documentSizeScaling) + "," + Math.round(this.lowerLeftY*documentSizeScaling);
    
      this.bottomCenter = this.lowerCenterX + "," + this.lowerCenterY;
     this.rightBottom = this.lowerRightX + "," + this.lowerRightY;
    
     this.leftCenter = this.middleLeftX + "," + this.middleLeftY;
     this.center = this.middleCenterX + "," + this.middleCenterY;
     this.rightCenter = this.middleRightX + "," + this.middleRightY;
          
            //only one that is used atm
     this.leftTop =  Math.round(this.upperLeftX*documentSizeScaling) + "," + Math.round(this.upperLeftY*documentSizeScaling);
    
      this.topCenter = this.upperCenterX + "," + this.upperCenterY;
     this.rightTop = this.upperRightX + "," + this.upperRightY;

   // these return object coordinates relative to layer bounds
      this.relUpperLeftX = layer.bounds[1].value - layer.bounds[1].value;
      this.relUpperLeftY =  layer.bounds[0].value - layer.bounds[0].value;
      this.relUpperCenterX = this.layerWidth / 2;
      this.relUpperCenterY = layer.bounds[0].value - layer.bounds[0].value;
      this.relUpperRightX = this.layerWidth;
      this.relUpperRightY = layer.bounds[0].value - layer.bounds[0].value;
      this.relMiddleLeftX = layer.bounds[1].value - layer.bounds[1].value;
      this.relMiddleLeftY = this.layerHeight / 2;
      this.relMiddleCenterX = this.layerWidth / 2;
      this.relMiddleCenterY = this.layerHeight / 2;
      this.relMiddleRightX = this.layerWidth;
    this.relMiddleRightY = this.layerHeight / 2;
      this.relLowerLeftX = layer.bounds[1].value - layer.bounds[1].value;
      this.relLowerLeftY = this.layerHeight;
      this.relLowerCenterX = this.layerWidth / 2;
    this.relLowerCenterY = this.layerHeight / 2;
      this.relLowerRightY = this.layerHeight;
      this.relLowerRightX = this.layerWidth;
      this.relLowerRightY = this.layerHeight;
 
  return this;
}

// now a function to collect the data
function exportBounds(newDoc, layer, i) {
    var isVisible = layer.visible;
    var layerData = cLayer(newDoc, layer);

  if(isVisible){
// Layer object main coordinates relative to its active pixels
    var str2 = "\t<image code=\"" + layer.name
   + "\" stack=\"" + (i - 1) // order in which layers are stacked, starting with zero for the bottom-most layer
   + "\" position=\"" + leftTop // this is the
   + "\" width=\"" + layerData.layerWidth
   + "\" height=\"" + layerData.layerHeight  + "\">"
   //+ "\" transformpoint=\"" + "center" + "\">" // hard-coding 'center' as the default transformation point
   + layer.name + ".png" + "</image>\n" // I have to put some content here otherwise sometimes tags are ignored
    //+ " />"
    str += str2.toString();
   };
};