Quantcast
Channel: Adobe Community: Message List - Photoshop Scripting
Viewing all articles
Browse latest Browse all 27456

Re: Create images with dynamic width from 3 images each (left/center/right-part)

$
0
0

I adapted a Script somewhat, so you may give this a test.

But it uses the open file so you would have to adapt it further.

// arranges the selected jpg, tif, psd in line;

// gutters may be irregular due to rounding effects;

// thanks to michael l hale and muppet mark;

// for mac and CS6;

// 2014, use it at your own risk;

#target photoshop

if (app.documents.length == 0) {

          var myDocument = app.documents.add(UnitValue (300, "mm"), UnitValue (50, "mm"), 300, "new", NewDocumentMode.RGB, DocumentFill.TRANSPARENT)

          }

else {myDocument = app.activeDocument};

// set to pixels;

var originalRulerUnits = app.preferences.rulerUnits;

app.preferences.rulerUnits = Units.PIXELS;

var theArray = [0, 0, myDocument.width, myDocument.height];

// select files;

if ($.os.search(/windows/i) != -1) {var theFiles = File.openDialog ("please select files", '*.jpg;*.tif;*.pdf;*.psd', true)}

else {var theFiles = File.openDialog ("please select exactly three files", getFiles, true)};

// do the arrangement

if (theFiles) {placeInLines (myDocument, theFiles, theArray)}

app.preferences.rulerUnits = originalRulerUnits;

////////////////////////////////////

////////////////////////////////////

////////////////////////////////////

////// function to place images in lines //////

function placeInLines (myDocument, theFiles, theArray) {

theFiles.sort();

// fit on screen;

var idslct = charIDToTypeID( "slct" );

var desc64 = new ActionDescriptor();

var idnull = charIDToTypeID( "null" );

var ref44 = new ActionReference();

var idMn = charIDToTypeID( "Mn  " );

var idMnIt = charIDToTypeID( "MnIt" );

var idFtOn = charIDToTypeID( "FtOn" );

ref44.putEnumerated( idMn, idMnIt, idFtOn );

desc64.putReference( idnull, ref44 );

executeAction( idslct, desc64, DialogModes.NO );

// change pref;

var originalRulerUnits = app.preferences.rulerUnits;

app.preferences.rulerUnits = Units.PIXELS;

setToAccelerated();

app.togglePalettes();

var check = turnOffRescale ();

// create the arrangement;

if (theFiles.length > 0 && theFiles.length == 3) {

myDocument.activeLayer = myDocument.layers[0];

// create masked group;

var theGroup = myDocument.layerSets.add();

theGroup.name = "arrangement";

// determine the array’s values;

var areaWidth = theArray[2] - theArray[0];

var areaHeight = theArray[3] - theArray[1];

var theDocResolution = myDocument.resolution;

var areaRelation = areaHeight / areaWidth;

// center of placed non-pdf images;

var centerX = Number(myDocument.width / 2);

var centerY = Number(myDocument.height / 2);

// suppress dialogs;

var theDialogSettings = app.displayDialogs;

app.displayDialogs = DialogModes.NO;

var pdfSinglePages = new Array;

var nonPDFs = new Array;

var theDimPDFs = new Array;

var theLength = 0;

// collect the files’ measurements;

var theDimensions = new Array;

var theLengths = new Array;

// array to collect both files and placed pdf-pages;

var theseFiles = new Array;

var theLength = 0;

// collect the files’ measurements;

for (var o = 0; o < theFiles.length; o++) {

    var thisFile = theFiles[o];

          theseFiles.push(thisFile);

          var theDim = getDimensions(thisFile);

          theDimensions.push(theDim);

          theRelativeWidth = 100 / theDim[1] * theDim[0];

          theLength = theLength + theRelativeWidth;

          };

// reset dialogmodes;

app.displayDialogs = DialogModes.ERROR;

// if three files;

if (theseFiles.length == 3) {

// create the layers;

var theNumber = 0;

var theAdded = 0;

var y = areaHeight / 2;

// add placed image’s width;

var thisLineWidth = 0 + theAdded;

var theLastFactor = Number (Number(myDocument.height) / theDimensions[2][1] * theDimensions[2][2] / theDocResolution * 100);

var theLastWidth = Math.round(theDimensions[2][0] * theLastFactor / 100 * theDocResolution / theDimensions[2][2]);

// place the files;

for (var x = 0; x < 3; x++) {

var theNumber = x;

var thisFile = theseFiles[theNumber];

var theFactor = Number (Number(myDocument.height) / theDimensions[theNumber][1] * theDimensions[theNumber][2] / theDocResolution * 100);

var theNewWidth = Math.round(theDimensions[theNumber][0] * theFactor / 100 * theDocResolution / theDimensions[theNumber][2]);

var offsetX = theNewWidth / 2 + thisLineWidth - centerX + theArray[0];

var offsetY = y - centerY + theArray[1];

var theLayer = placeScaleFile (thisFile, offsetX, offsetY, theFactor, theFactor);

myDocument.activeLayer.move(theGroup, ElementPlacement.PLACEATBEGINNING);

thisLineWidth = thisLineWidth + theNewWidth;

// duplicate the middle one;

if (theNumber == 1) {

          while (thisLineWidth < myDocument.width - theLastWidth) {

                    theLayer = duplicateAndOffset (theLayer, theNewWidth, 0);

                    thisLineWidth = thisLineWidth + theNewWidth;

                    }

          }

}

}

};

// reset;

app.togglePalettes();

turnOnRescale (check);

app.preferences.rulerUnits = originalRulerUnits;

};

////////////////////////////////////

////////////////////////////////////

////////////////////////////////////

////// playback to accelerated //////

function setToAccelerated () {

          var idsetd = charIDToTypeID( "setd" );

          var desc1 = new ActionDescriptor();

          var idnull = charIDToTypeID( "null" );

                    var ref1 = new ActionReference();

                    var idPrpr = charIDToTypeID( "Prpr" );

                    var idPbkO = charIDToTypeID( "PbkO" );

                    ref1.putProperty( idPrpr, idPbkO );

                    var idcapp = charIDToTypeID( "capp" );

                    var idOrdn = charIDToTypeID( "Ordn" );

                    var idTrgt = charIDToTypeID( "Trgt" );

                    ref1.putEnumerated( idcapp, idOrdn, idTrgt );

          desc1.putReference( idnull, ref1 );

          var idT = charIDToTypeID( "T   " );

                    var desc2 = new ActionDescriptor();

                    var idperformance = stringIDToTypeID( "performance" );

                    var idperformance = stringIDToTypeID( "performance" );

                    var idaccelerated = stringIDToTypeID( "accelerated" );

                    desc2.putEnumerated( idperformance, idperformance, idaccelerated );

          var idPbkO = charIDToTypeID( "PbkO" );

          desc1.putObject( idT, idPbkO, desc2 );

          executeAction( idsetd, desc1, DialogModes.NO );

          };

////// get psds, tifs and jpgs from files //////

function getFiles (theFile) {

    if (theFile.name.match(/\.(jpg|tif|psd|pdf|)$/i)) {

        return true

        };

          };

////// place //////

function placeScaleFile (file, xOffset, yOffset, theScale) {

// =======================================================

var idPlc = charIDToTypeID( "Plc " );

    var desc5 = new ActionDescriptor();

    var idnull = charIDToTypeID( "null" );

    desc5.putPath( idnull, new File( file ) );

    var idFTcs = charIDToTypeID( "FTcs" );

    var idQCSt = charIDToTypeID( "QCSt" );

    var idQcsa = charIDToTypeID( "Qcsa" );

    desc5.putEnumerated( idFTcs, idQCSt, idQcsa );

    var idOfst = charIDToTypeID( "Ofst" );

        var desc6 = new ActionDescriptor();

        var idHrzn = charIDToTypeID( "Hrzn" );

        var idPxl = charIDToTypeID( "#Pxl" );

        desc6.putUnitDouble( idHrzn, idPxl, xOffset );

        var idVrtc = charIDToTypeID( "Vrtc" );

        var idPxl = charIDToTypeID( "#Pxl" );

        desc6.putUnitDouble( idVrtc, idPxl, yOffset );

    var idOfst = charIDToTypeID( "Ofst" );

    desc5.putObject( idOfst, idOfst, desc6 );

    var idWdth = charIDToTypeID( "Wdth" );

    var idPrc = charIDToTypeID( "#Prc" );

    desc5.putUnitDouble( idWdth, idPrc, theScale );

    var idHght = charIDToTypeID( "Hght" );

    var idPrc = charIDToTypeID( "#Prc" );

    desc5.putUnitDouble( idHght, idPrc, theScale );

    var idLnkd = charIDToTypeID( "Lnkd" );

    desc5.putBoolean( idLnkd, true );

executeAction( idPlc, desc5, DialogModes.NO );

return myDocument.activeLayer;

};

////// open pdf //////

function openPDF (theImage, x) {

// define pdfopenoptions;

var pdfOpenOpts = new PDFOpenOptions;

pdfOpenOpts.antiAlias = true;

pdfOpenOpts.bitsPerChannel = BitsPerChannelType.EIGHT;

pdfOpenOpts.cropPage = CropToType.TRIMBOX;

pdfOpenOpts.mode = OpenDocumentMode.CMYK;

pdfOpenOpts.resolution = 10;

pdfOpenOpts.suppressWarnings = true;

pdfOpenOpts.usePageNumber  = true;

// suppress dialogs;

var theDialogSettings = app.displayDialogs;

app.displayDialogs = DialogModes.NO;

//

pdfOpenOpts.page = x;

var thePdf = app.open(theImage, pdfOpenOpts);

thePdf.close(SaveOptions.DONOTSAVECHANGES);

// reset dialogmodes;

app.displayDialogs = theDialogSettings;

};

 

 

////// turn off preference to scale placed image //////

function turnOffRescale () {

// determine if the resize prefernce is on;

var ref = new ActionReference();

ref.putEnumerated( charIDToTypeID("capp"), charIDToTypeID("Ordn"), charIDToTypeID("Trgt") );

var appDesc = executeActionGet(ref);

var prefDesc = appDesc.getObjectValue(charIDToTypeID( "GnrP" ));

var theResizePref = prefDesc.getBoolean(stringIDToTypeID( "resizePastePlace" ));

// turn off resize image during place;

if (theResizePref == true);{

// =======================================================

var idsetd = charIDToTypeID( "setd" );

    var desc12 = new ActionDescriptor();

    var idnull = charIDToTypeID( "null" );

        var ref4 = new ActionReference();

        var idPrpr = charIDToTypeID( "Prpr" );

        var idGnrP = charIDToTypeID( "GnrP" );

        ref4.putProperty( idPrpr, idGnrP );

        var idcapp = charIDToTypeID( "capp" );

        var idOrdn = charIDToTypeID( "Ordn" );

        var idTrgt = charIDToTypeID( "Trgt" );

        ref4.putEnumerated( idcapp, idOrdn, idTrgt );

    desc12.putReference( idnull, ref4 );

    var idT = charIDToTypeID( "T   " );

        var desc13 = new ActionDescriptor();

        var idresizePastePlace = stringIDToTypeID( "resizePastePlace" );

        desc13.putBoolean( idresizePastePlace, false );

    var idGnrP = charIDToTypeID( "GnrP" );

    desc12.putObject( idT, idGnrP, desc13 );

executeAction( idsetd, desc12, DialogModes.NO );

};

return theResizePref

};

////// turn on preference to scale plced image //////

function turnOnRescale (check) {

if (check == true) {

// =======================================================

var idsetd = charIDToTypeID( "setd" );

    var desc14 = new ActionDescriptor();

    var idnull = charIDToTypeID( "null" );

        var ref5 = new ActionReference();

        var idPrpr = charIDToTypeID( "Prpr" );

        var idGnrP = charIDToTypeID( "GnrP" );

        ref5.putProperty( idPrpr, idGnrP );

        var idcapp = charIDToTypeID( "capp" );

        var idOrdn = charIDToTypeID( "Ordn" );

        var idTrgt = charIDToTypeID( "Trgt" );

        ref5.putEnumerated( idcapp, idOrdn, idTrgt );

    desc14.putReference( idnull, ref5 );

    var idT = charIDToTypeID( "T   " );

        var desc15 = new ActionDescriptor();

        var idresizePastePlace = stringIDToTypeID( "resizePastePlace" );

        desc15.putBoolean( idresizePastePlace, true );

    var idGnrP = charIDToTypeID( "GnrP" );

    desc14.putObject( idT, idGnrP, desc15 );

executeAction( idsetd, desc14, DialogModes.NO );

}

};

////// convert to so if not one aready //////

function duplicateAndOffset (theLayer, theXOffset, theYOffset) {

app.activeDocument.activeLayer = theLayer;

// =======================================================

var idcopy = charIDToTypeID( "copy" );

    var desc9 = new ActionDescriptor();

    var idnull = charIDToTypeID( "null" );

        var ref5 = new ActionReference();

        var idLyr = charIDToTypeID( "Lyr " );

        var idOrdn = charIDToTypeID( "Ordn" );

        var idTrgt = charIDToTypeID( "Trgt" );

        ref5.putEnumerated( idLyr, idOrdn, idTrgt );

    desc9.putReference( idnull, ref5 );

    var idT = charIDToTypeID( "T   " );

        var desc10 = new ActionDescriptor();

        var idHrzn = charIDToTypeID( "Hrzn" );

        var idRlt = charIDToTypeID( "#Pxl" );

        desc10.putUnitDouble( idHrzn, idRlt, theXOffset );

        var idVrtc = charIDToTypeID( "Vrtc" );

        var idRlt = charIDToTypeID( "#Pxl" );

        desc10.putUnitDouble( idVrtc, idRlt, theYOffset );

    var idOfst = charIDToTypeID( "Ofst" );

    desc9.putObject( idT, idOfst, desc10 );

executeAction( idcopy, desc9, DialogModes.NO );

return app.activeDocument.activeLayer

};

////// load pdf as smart object //////

function transformLayer (layer, percentage, xOffset, yOffset) {

app.activeDocument.activeLayer = layer;

// =======================================================

var idTrnf = charIDToTypeID( "Trnf" );

    var desc4 = new ActionDescriptor();

    var idFTcs = charIDToTypeID( "FTcs" );

    var idQCSt = charIDToTypeID( "QCSt" );

    var idQcsa = charIDToTypeID( "Qcsa" );

    desc4.putEnumerated( idFTcs, idQCSt, idQcsa );

    var idOfst = charIDToTypeID( "Ofst" );

        var desc5 = new ActionDescriptor();

        var idHrzn = charIDToTypeID( "Hrzn" );

        var idPxl = charIDToTypeID( "#Pxl" );

        desc5.putUnitDouble( idHrzn, idPxl, xOffset );

        var idVrtc = charIDToTypeID( "Vrtc" );

        var idPxl = charIDToTypeID( "#Pxl" );

        desc5.putUnitDouble( idVrtc, idPxl, yOffset );

    var idOfst = charIDToTypeID( "Ofst" );

    desc4.putObject( idOfst, idOfst, desc5 );

    var idWdth = charIDToTypeID( "Wdth" );

    var idPrc = charIDToTypeID( "#Prc" );

    desc4.putUnitDouble( idWdth, idPrc, percentage );

    var idHght = charIDToTypeID( "Hght" );

    var idPrc = charIDToTypeID( "#Prc" );

    desc4.putUnitDouble( idHght, idPrc, percentage );

    var idLnkd = charIDToTypeID( "Lnkd" );

    desc4.putBoolean( idLnkd, true );

    var idAntA = charIDToTypeID( "AntA" );

    desc4.putBoolean( idAntA, true );

executeAction( idTrnf, desc4, DialogModes.NO );

//

return app.activeDocument.activeLayer

};

////// function to get file’s dimensions, thanks to michael l hale //////

function getDimensions( file ){

////////////////////////////////////

function divideString (theString) {

          theString = String(theString);

    var a = Number(theString.slice(0, theString.indexOf("\/")));

    var b = Number(theString.slice(theString.indexOf("\/") + 1));

    return (a / b)

    };

// from a script by michael l hale;

function loadXMPLibrary(){

     if ( !ExternalObject.AdobeXMPScript ){

          try{

               ExternalObject.AdobeXMPScript = new ExternalObject

                                                            ('lib:AdobeXMPScript');

          }catch (e){

               alert( ErrStrs.XMPLIB );

               return false;

          }

     }

     return true;

};

function unloadXMPLibrary(){

   if( ExternalObject.AdobeXMPScript ) {

      try{

         ExternalObject.AdobeXMPScript.unload();

         ExternalObject.AdobeXMPScript = undefined;

      }catch (e){

         alert( ErrStrs.XMPLIB );

      }

   }

};

////// based on a script by muppet mark //////

function dimensionsShellScript (file) {

          try {

// getMetaDataMDLS;

if (File(file) instanceof File && File(file).exists) {

          var shellString = "/usr/bin/mdls ";

          shellString += File(file).fsName;

//          shellString += File(file).fullName;

          shellString += ' > ~/Documents/StdOut2.txt';

          app.system(shellString);

          };

// read the file;

if (File('~/Documents/StdOut2.txt').exists == true) {

    var file = File('~/Documents/StdOut2.txt');

    file.open("r");

    file.encoding= 'BINARY';

    var theText = new String;

    for (var m = 0; m < file.length; m ++) {

                    theText = theText.concat(file.readch());

                    };

          file.close();

          theText = theText.split("\n");

          };

// get the dimensions;

          var dim = new Array;

          for (var m = 0; m < theText.length; m++) {

                    var theLine = theText[m];

                    if (theLine.indexOf("kMDItemPixelWidth") != -1) {dim.push(theLine.match(/[\d\.]+/g).join("") )}

                    if (theLine.indexOf("kMDItemPixelHeight") != -1) {dim.push(theLine.match(/[\d\.]+/g).join("") )}

                    if (theLine.indexOf("kMDItemResolutionWidthDPI") != -1) {dim.push(theLine.match(/[\d\.]+/g).join("") )}

                    if (theLine.indexOf("kMDItemResolutionHeightDPI") != -1) {dim.push(theLine.match(/[\d\.]+/g).join("") )}

                    };

// remove file and hand back;

          File('~/Documents/StdOut2.txt').remove();

          }

catch (e) {

          if (File('~/Documents/StdOut2.txt').exists == true) {File('~/Documents/StdOut2.txt').remove()};

          };

          return dim

          };

////////////////////////////////////

          try{

                    loadXMPLibrary();

                    var xmpf = new XMPFile( file.fsName, XMPConst.UNKNOWN, XMPConst.OPEN_FOR_READ );

                    var xmp = xmpf.getXMP();

                    xmpf.closeFile();

 

                    var resolutionUnit = xmp.getProperty( XMPConst.NS_TIFF, 'ResolutionUnit', XMPConst.STRING);

                    var resFactor = 1;

                    if (resolutionUnit == 2) {

                              var resFactor = 1;

                              };

                    if (resolutionUnit == 3) {

                              var resFactor = 2.54;

                              };

 

                    var dim = [xmp.getProperty( XMPConst.NS_EXIF, 'PixelXDimension', XMPConst.STRING),

                    xmp.getProperty( XMPConst.NS_EXIF, 'PixelYDimension', XMPConst.STRING),

                    divideString (xmp.getProperty( XMPConst.NS_TIFF, 'XResolution', XMPConst.STRING)) * resFactor,

                    divideString (xmp.getProperty( XMPConst.NS_TIFF, 'YResolution', XMPConst.STRING)) * resFactor];

                    unloadXMPLibrary();

                    if(dim[0]=="undefined" || dim[1]=="undefined"){

            var dim = undefined;

            var res = undefined;

            var bt = new BridgeTalk;

            bt.target = "bridge";

            var myScript = ("var ftn = " + psRemote.toSource() + "; ftn("+file.toSource()+");");

            bt.body = myScript;

            bt.onResult = function( inBT ) {myReturnValue(inBT.body); }

            bt.send(10);

 

                    function myReturnValue(str){

                              res = str;

                              dim = str.split(',');

                              };

 

 

                    function psRemote(file){

                              var t= new Thumbnail(file);

                              return t.core.quickMetadata.width+','+t.core.quickMetadata.height;

                              };

        }

    }catch(e){unloadXMPLibrary()};

////////////////////////////////////

          if (String(dim[2]).indexOf("\/") != -1) {

                    var a = divideString(dim[2]);

                    var b = divideString(dim[3]);

                    dim = [dim[0], dim[1], a, b]

                    };

// if dimensions are missing as might be the case with some bitmap tiffs for example try a shell-script;

          if (dim[0] == undefined || dim[1] == undefined) {

                    var array = dimensionsShellScript(file);

                    dim = array;

                    };

// if shell-string failed open doc to get measurements;

          if (dim[0] == undefined || dim[1] == undefined) {

                    var thisDoc = app.open (File(file));

// close ai without saving;

                    if (file.name.slice(-3).match(/\.(ai)$/i)) {

                              thisDoc.trim(TrimType.TRANSPARENT);

                              var dim = [thisDoc.width, thisDoc.height, thisDoc.resolution, thisDoc.resolution];

                              thisDoc.close(SaveOptions.DONOTSAVECHANGES)

                              }

                    else {

                              var dim = [thisDoc.width, thisDoc.height, thisDoc.resolution, thisDoc.resolution];

                              thisDoc.close(SaveOptions.PROMPTTOSAVECHANGES)

                              }

                    };

////////////////////////////////////

return dim;

};


Viewing all articles
Browse latest Browse all 27456

Trending Articles