script for arrangement of images
Posted: Sun Mar 13, 2011 10:35 am
It would be nice if someone could give this Script a look-over to see if I have overlooked something regarding either performance or logic.
It is an arrangement-script that attempts to arrange selected psd-, tif-, jpg- and pdf-files in lines within the rectangular bounds of a Selection or in relation to an open file’s dimensions.
Michael L Hale and Muppet Mark thankworthily provided help with getting images’ dimensions before placing them, which I think speeded up the Script’s performance considerably.
As for multi-page pdfs I used the easier way of opening them with a try-clause to get their page-number, because while some time ago I also received help from various posters regarding the evaluation pdf-pagecounts none of the methods seemed to be successful with all possible issues pdfs may provide.
Thanks in advance,
regards,
pfaffenbichler
Code: Select all// arranges the selected jpg, tif, psd and pdf in lines of the same height without margins within the bounds of a selection or a set boundary within the file;
// thanks to michael l hale and muppet mark;
// to avoid the trouble of determining pdf-page counts and potential problems with pdfs with differently sized pages pdfs are temporarily opened, then placed;
// for CS5;
// 2011, use it at your own risk;
#target photoshop
if (app.documents.length == 0) {
var myDocument = app.documents.add(UnitValue (210, "mm"), UnitValue (297, "mm"), 300, "new", NewDocumentMode.RGB, DocumentFill.TRANSPARENT)
}
else {myDocument = app.activeDocument};
// set to pixels;
var originalRulerUnits = app.preferences.rulerUnits;
app.preferences.rulerUnits = Units.PIXELS;
// get selection bounds or create array based on image’s size;
try {var theArray = myDocument.selection.bounds}
catch (e) {var theArray = [50, 50, myDocument.width - 50, myDocument.height - 50]};
if ( theArray[2] - theArray[0] > 10 && theArray[3] - theArray[1] > 10) {
// select files;
var theFiles = File.openDialog ("please select files", getFiles, true);
// do the arrangement
if (theFiles) {placeInLines (myDocument, theFiles, theArray)}
}
else {alert ("file to small")};
app.preferences.rulerUnits = originalRulerUnits;
////////////////////////////////////
////////////////////////////////////
////////////////////////////////////
////// function to place images in lines //////
function placeInLines (myDocument, theFiles, theArray) {
// 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) {
myDocument.activeLayer = myDocument.layers[0];
// create masked group;
var theGroup = myDocument.layerSets.add();
myDocument.selection.select([[theArray[0], theArray[1]], [theArray[2], theArray[1]], [theArray[2], theArray[3]], [theArray[0], theArray[3]]]);
addLayerMask();
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 pdf files’ measurements;
for (var o = 0; o < theFiles.length; o++) {
var thisFile = theFiles[o];
// check for pdf;
if (thisFile.name.slice(-4).match(/\.(pdf)$/i)) {
// determine the number of elements;
var myCounter = 1;
var myBreak = false;
while(myBreak == false) {
try {
// open and close to check if page exists;
openPDF (thisFile, myCounter);
// place as so;
var thePlaced = placePDFPage(thisFile, myCounter, theGroup);
thePlaced.name = thisFile.name + myCounter;
var width = thePlaced.bounds[2] - thePlaced.bounds[0];
var height = thePlaced.bounds[3] - thePlaced.bounds[1];
theDimensions.push([width, height, myDocument.resolution, myDocument.resolution]);
theRelativeWidth = 100 / height * width;
theLength = theLength + theRelativeWidth;
myCounter++;
// enter the new file into the array;
theseFiles.push(thePlaced);
}
catch (e) {myBreak = true};
};
};
else {
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;
// get relation of height and width;
var theFilesRelation = 100 / theLength;
// determine the necessary number of lines and the heights;
var linesNumber = Math.ceil(Math.sqrt(1 / (100 / theLength / areaRelation)));
var theLineHeight = Math.round(areaHeight / linesNumber);
var theLineHeightC = Math.ceil(areaHeight / linesNumber);
// create the layers;
var theNumber = 0;
var theAdded = 0;
var y = theLineHeight / 2;
var theLinesDone = 0;
var repeat = false;
// go through the bunch;
while (theLinesDone < linesNumber) {
// add placed image’s width;
var thisLineWidth = 0 + theAdded;
// get the vertical offset;
if (theLinesDone != 0) {y = y + theLineHeight};
//
while (thisLineWidth < areaWidth && theNumber < theseFiles.length) {
var thisFile = theseFiles[theNumber];
// if placed layer from pdfs;
if (thisFile.typename == "ArtLayer") {
var theFactor = Number (theLineHeightC / theDimensions[theNumber][1] * theDimensions[theNumber][2] / theDocResolution * 100);
var theNewWidth = Math.round(theDimensions[theNumber][0] * theFactor / 100 * theDocResolution / theDimensions[theNumber][2]);
// if image has not yet been used;
if (repeat == false) {
var offsetX = theNewWidth / 2 + thisLineWidth - centerX + theArray[0];
var offsetY = y - centerY + theArray[1];
var theLayer = transformLayer (thisFile, theFactor, offsetX, offsetY);
}
// if image has already been placed before;
else {
var offsetX = theNewWidth / 2 + thisLineWidth - ((thisFile.bounds[2] - thisFile.bounds[0]) / 2 + thisFile.bounds[0]) + theArray[0];
var offsetY = y - ((thisFile.bounds[3] - thisFile.bounds[1]) / 2 + thisFile.bounds[1]) + theArray[1];
var theLayer = thisFile.duplicate(theGroup, ElementPlacement.PLACEATBEGINNING);
theLayer.translate(offsetX, offsetY * (-1) + theArray[1] * 2);
}
}
// if file;
else {
var theFactor = Number (theLineHeightC / 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)
};
// increase the count for images;
theNumber++;
thisLineWidth = thisLineWidth + theNewWidth;
// rasterize the layer to reduce file size;
var theLayer = rasterize(theLayer);
// if scaled image is wider than the document;
if (theNewWidth > areaWidth && theLinesDone < linesNumber) {
while (thisLineWidth > areaWidth) {
var theLayer = theLayer.duplicate(theLayer, ElementPlacement.PLACEBEFORE);
myDocument.activeLayer = theLayer;
theLayer.translate (areaWidth * (-1), theLineHeight);
var theAdded = theLayer.bounds[2] - theArray[0];
thisLineWidth = theLayer.bounds[2] - theArray[0];
y = y + theLineHeight;
theLinesDone++
}
}
else {
// if line overreaches the edge, copy and move to next line;
if (thisLineWidth > areaWidth && theLinesDone < linesNumber) {
var theLayer = theLayer.duplicate(theLayer, ElementPlacement.PLACEBEFORE);
myDocument.activeLayer = theLayer;
theLayer.translate (areaWidth * (-1), theLineHeight);
var theAdded = theLayer.bounds[2] - theArray[0];
}
};
// loop back to the first image;
if (theNumber == theseFiles.length) {
if (repeat == false) {
var repeat = confirm("repeat images to fill format?", false, "repeat")
};
if (repeat == true) {theNumber = 0}
};
};
// increase the count for lines;
theLinesDone++
};
};
// reset;
app.togglePalettes();
turnOnRescale (check);
app.preferences.rulerUnits = originalRulerUnits;
};
////////////////////////////////////
////////////////////////////////////
////////////////////////////////////
////// add layer mask //////
function addLayerMask () {
var idMk = charIDToTypeID( "Mk " );
var desc168 = new ActionDescriptor();
var idNw = charIDToTypeID( "Nw " );
var idChnl = charIDToTypeID( "Chnl" );
desc168.putClass( idNw, idChnl );
var idAt = charIDToTypeID( "At " );
var ref99 = new ActionReference();
var idChnl = charIDToTypeID( "Chnl" );
var idChnl = charIDToTypeID( "Chnl" );
var idMsk = charIDToTypeID( "Msk " );
ref99.putEnumerated( idChnl, idChnl, idMsk );
desc168.putReference( idAt, ref99 );
var idUsng = charIDToTypeID( "Usng" );
var idUsrM = charIDToTypeID( "UsrM" );
var idRvlS = charIDToTypeID( "RvlS" );
desc168.putEnumerated( idUsng, idUsrM, idRvlS );
executeAction( idMk, desc168, DialogModes.NO );
// unlink;
// =======================================================
var idsetd = charIDToTypeID( "setd" );
var desc10 = new ActionDescriptor();
var idnull = charIDToTypeID( "null" );
var ref3 = new ActionReference();
var idLyr = charIDToTypeID( "Lyr " );
var idOrdn = charIDToTypeID( "Ordn" );
var idTrgt = charIDToTypeID( "Trgt" );
ref3.putEnumerated( idLyr, idOrdn, idTrgt );
desc10.putReference( idnull, ref3 );
var idT = charIDToTypeID( "T " );
var desc11 = new ActionDescriptor();
var idUsrs = charIDToTypeID( "Usrs" );
desc11.putBoolean( idUsrs, false );
var idLyr = charIDToTypeID( "Lyr " );
desc10.putObject( idT, idLyr, desc11 );
executeAction( idsetd, desc10, DialogModes.NO );
};
////// 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;
};
////// place a pdf //////
function placePDFPage (theImage, x, theLayerSet) {
// =======================================================
var idPlc = charIDToTypeID( "Plc " );
var desc3 = new ActionDescriptor();
var idAs = charIDToTypeID( "As " );
var desc4 = new ActionDescriptor();
var idfsel = charIDToTypeID( "fsel" );
var idpdfSelection = stringIDToTypeID( "pdfSelection" );
var idpage = stringIDToTypeID( "page" );
desc4.putEnumerated( idfsel, idpdfSelection, idpage );
var idPgNm = charIDToTypeID( "PgNm" );
desc4.putInteger( idPgNm, x );
var idCrop = charIDToTypeID( "Crop" );
var idcropTo = stringIDToTypeID( "cropTo" );
var idtrimBox = stringIDToTypeID( "trimBox" );
desc4.putEnumerated( idCrop, idcropTo, idtrimBox );
var idPDFG = charIDToTypeID( "PDFG" );
desc3.putObject( idAs, idPDFG, desc4 );
var idnull = charIDToTypeID( "null" );
desc3.putPath( idnull, new File( theImage ) );
var idFTcs = charIDToTypeID( "FTcs" );
var idQCSt = charIDToTypeID( "QCSt" );
var idQcsa = charIDToTypeID( "Qcsa" );
desc3.putEnumerated( idFTcs, idQCSt, idQcsa );
var idOfst = charIDToTypeID( "Ofst" );
var desc5 = new ActionDescriptor();
var idHrzn = charIDToTypeID( "Hrzn" );
var idRlt = charIDToTypeID( "#Rlt" );
desc5.putUnitDouble( idHrzn, idRlt, 0.000000 );
var idVrtc = charIDToTypeID( "Vrtc" );
var idRlt = charIDToTypeID( "#Rlt" );
desc5.putUnitDouble( idVrtc, idRlt, -0.000000 );
var idOfst = charIDToTypeID( "Ofst" );
desc3.putObject( idOfst, idOfst, desc5 );
var idAntA = charIDToTypeID( "AntA" );
desc3.putBoolean( idAntA, true );
executeAction( idPlc, desc3, DialogModes.NO );
// move forward;
app.activeDocument.activeLayer.move(theLayerSet, ElementPlacement.PLACEATBEGINNING);
return app.activeDocument.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;
};
////// rasterize //////
function rasterize (theLayer) {
app.activeDocument.activeLayer = theLayer;
if (theLayer.kind == LayerKind.SMARTOBJECT) {
// rasterize;
var id631 = charIDToTypeID( "slct" );
var desc125 = new ActionDescriptor();
var id632 = charIDToTypeID( "null" );
var ref83 = new ActionReference();
var id633 = charIDToTypeID( "Mn " );
var id634 = charIDToTypeID( "MnIt" );
var id635 = stringIDToTypeID( "rasterizePlaced" );
ref83.putEnumerated( id633, id634, id635 );
desc125.putReference( id632, ref83 );
executeAction( id631, desc125, DialogModes.NO );
};
return app.activeDocument.activeLayer
};
////// 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 );
}
};
////// 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;
};
It is an arrangement-script that attempts to arrange selected psd-, tif-, jpg- and pdf-files in lines within the rectangular bounds of a Selection or in relation to an open file’s dimensions.
Michael L Hale and Muppet Mark thankworthily provided help with getting images’ dimensions before placing them, which I think speeded up the Script’s performance considerably.
As for multi-page pdfs I used the easier way of opening them with a try-clause to get their page-number, because while some time ago I also received help from various posters regarding the evaluation pdf-pagecounts none of the methods seemed to be successful with all possible issues pdfs may provide.
Thanks in advance,
regards,
pfaffenbichler
Code: Select all// arranges the selected jpg, tif, psd and pdf in lines of the same height without margins within the bounds of a selection or a set boundary within the file;
// thanks to michael l hale and muppet mark;
// to avoid the trouble of determining pdf-page counts and potential problems with pdfs with differently sized pages pdfs are temporarily opened, then placed;
// for CS5;
// 2011, use it at your own risk;
#target photoshop
if (app.documents.length == 0) {
var myDocument = app.documents.add(UnitValue (210, "mm"), UnitValue (297, "mm"), 300, "new", NewDocumentMode.RGB, DocumentFill.TRANSPARENT)
}
else {myDocument = app.activeDocument};
// set to pixels;
var originalRulerUnits = app.preferences.rulerUnits;
app.preferences.rulerUnits = Units.PIXELS;
// get selection bounds or create array based on image’s size;
try {var theArray = myDocument.selection.bounds}
catch (e) {var theArray = [50, 50, myDocument.width - 50, myDocument.height - 50]};
if ( theArray[2] - theArray[0] > 10 && theArray[3] - theArray[1] > 10) {
// select files;
var theFiles = File.openDialog ("please select files", getFiles, true);
// do the arrangement
if (theFiles) {placeInLines (myDocument, theFiles, theArray)}
}
else {alert ("file to small")};
app.preferences.rulerUnits = originalRulerUnits;
////////////////////////////////////
////////////////////////////////////
////////////////////////////////////
////// function to place images in lines //////
function placeInLines (myDocument, theFiles, theArray) {
// 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) {
myDocument.activeLayer = myDocument.layers[0];
// create masked group;
var theGroup = myDocument.layerSets.add();
myDocument.selection.select([[theArray[0], theArray[1]], [theArray[2], theArray[1]], [theArray[2], theArray[3]], [theArray[0], theArray[3]]]);
addLayerMask();
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 pdf files’ measurements;
for (var o = 0; o < theFiles.length; o++) {
var thisFile = theFiles[o];
// check for pdf;
if (thisFile.name.slice(-4).match(/\.(pdf)$/i)) {
// determine the number of elements;
var myCounter = 1;
var myBreak = false;
while(myBreak == false) {
try {
// open and close to check if page exists;
openPDF (thisFile, myCounter);
// place as so;
var thePlaced = placePDFPage(thisFile, myCounter, theGroup);
thePlaced.name = thisFile.name + myCounter;
var width = thePlaced.bounds[2] - thePlaced.bounds[0];
var height = thePlaced.bounds[3] - thePlaced.bounds[1];
theDimensions.push([width, height, myDocument.resolution, myDocument.resolution]);
theRelativeWidth = 100 / height * width;
theLength = theLength + theRelativeWidth;
myCounter++;
// enter the new file into the array;
theseFiles.push(thePlaced);
}
catch (e) {myBreak = true};
};
};
else {
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;
// get relation of height and width;
var theFilesRelation = 100 / theLength;
// determine the necessary number of lines and the heights;
var linesNumber = Math.ceil(Math.sqrt(1 / (100 / theLength / areaRelation)));
var theLineHeight = Math.round(areaHeight / linesNumber);
var theLineHeightC = Math.ceil(areaHeight / linesNumber);
// create the layers;
var theNumber = 0;
var theAdded = 0;
var y = theLineHeight / 2;
var theLinesDone = 0;
var repeat = false;
// go through the bunch;
while (theLinesDone < linesNumber) {
// add placed image’s width;
var thisLineWidth = 0 + theAdded;
// get the vertical offset;
if (theLinesDone != 0) {y = y + theLineHeight};
//
while (thisLineWidth < areaWidth && theNumber < theseFiles.length) {
var thisFile = theseFiles[theNumber];
// if placed layer from pdfs;
if (thisFile.typename == "ArtLayer") {
var theFactor = Number (theLineHeightC / theDimensions[theNumber][1] * theDimensions[theNumber][2] / theDocResolution * 100);
var theNewWidth = Math.round(theDimensions[theNumber][0] * theFactor / 100 * theDocResolution / theDimensions[theNumber][2]);
// if image has not yet been used;
if (repeat == false) {
var offsetX = theNewWidth / 2 + thisLineWidth - centerX + theArray[0];
var offsetY = y - centerY + theArray[1];
var theLayer = transformLayer (thisFile, theFactor, offsetX, offsetY);
}
// if image has already been placed before;
else {
var offsetX = theNewWidth / 2 + thisLineWidth - ((thisFile.bounds[2] - thisFile.bounds[0]) / 2 + thisFile.bounds[0]) + theArray[0];
var offsetY = y - ((thisFile.bounds[3] - thisFile.bounds[1]) / 2 + thisFile.bounds[1]) + theArray[1];
var theLayer = thisFile.duplicate(theGroup, ElementPlacement.PLACEATBEGINNING);
theLayer.translate(offsetX, offsetY * (-1) + theArray[1] * 2);
}
}
// if file;
else {
var theFactor = Number (theLineHeightC / 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)
};
// increase the count for images;
theNumber++;
thisLineWidth = thisLineWidth + theNewWidth;
// rasterize the layer to reduce file size;
var theLayer = rasterize(theLayer);
// if scaled image is wider than the document;
if (theNewWidth > areaWidth && theLinesDone < linesNumber) {
while (thisLineWidth > areaWidth) {
var theLayer = theLayer.duplicate(theLayer, ElementPlacement.PLACEBEFORE);
myDocument.activeLayer = theLayer;
theLayer.translate (areaWidth * (-1), theLineHeight);
var theAdded = theLayer.bounds[2] - theArray[0];
thisLineWidth = theLayer.bounds[2] - theArray[0];
y = y + theLineHeight;
theLinesDone++
}
}
else {
// if line overreaches the edge, copy and move to next line;
if (thisLineWidth > areaWidth && theLinesDone < linesNumber) {
var theLayer = theLayer.duplicate(theLayer, ElementPlacement.PLACEBEFORE);
myDocument.activeLayer = theLayer;
theLayer.translate (areaWidth * (-1), theLineHeight);
var theAdded = theLayer.bounds[2] - theArray[0];
}
};
// loop back to the first image;
if (theNumber == theseFiles.length) {
if (repeat == false) {
var repeat = confirm("repeat images to fill format?", false, "repeat")
};
if (repeat == true) {theNumber = 0}
};
};
// increase the count for lines;
theLinesDone++
};
};
// reset;
app.togglePalettes();
turnOnRescale (check);
app.preferences.rulerUnits = originalRulerUnits;
};
////////////////////////////////////
////////////////////////////////////
////////////////////////////////////
////// add layer mask //////
function addLayerMask () {
var idMk = charIDToTypeID( "Mk " );
var desc168 = new ActionDescriptor();
var idNw = charIDToTypeID( "Nw " );
var idChnl = charIDToTypeID( "Chnl" );
desc168.putClass( idNw, idChnl );
var idAt = charIDToTypeID( "At " );
var ref99 = new ActionReference();
var idChnl = charIDToTypeID( "Chnl" );
var idChnl = charIDToTypeID( "Chnl" );
var idMsk = charIDToTypeID( "Msk " );
ref99.putEnumerated( idChnl, idChnl, idMsk );
desc168.putReference( idAt, ref99 );
var idUsng = charIDToTypeID( "Usng" );
var idUsrM = charIDToTypeID( "UsrM" );
var idRvlS = charIDToTypeID( "RvlS" );
desc168.putEnumerated( idUsng, idUsrM, idRvlS );
executeAction( idMk, desc168, DialogModes.NO );
// unlink;
// =======================================================
var idsetd = charIDToTypeID( "setd" );
var desc10 = new ActionDescriptor();
var idnull = charIDToTypeID( "null" );
var ref3 = new ActionReference();
var idLyr = charIDToTypeID( "Lyr " );
var idOrdn = charIDToTypeID( "Ordn" );
var idTrgt = charIDToTypeID( "Trgt" );
ref3.putEnumerated( idLyr, idOrdn, idTrgt );
desc10.putReference( idnull, ref3 );
var idT = charIDToTypeID( "T " );
var desc11 = new ActionDescriptor();
var idUsrs = charIDToTypeID( "Usrs" );
desc11.putBoolean( idUsrs, false );
var idLyr = charIDToTypeID( "Lyr " );
desc10.putObject( idT, idLyr, desc11 );
executeAction( idsetd, desc10, DialogModes.NO );
};
////// 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;
};
////// place a pdf //////
function placePDFPage (theImage, x, theLayerSet) {
// =======================================================
var idPlc = charIDToTypeID( "Plc " );
var desc3 = new ActionDescriptor();
var idAs = charIDToTypeID( "As " );
var desc4 = new ActionDescriptor();
var idfsel = charIDToTypeID( "fsel" );
var idpdfSelection = stringIDToTypeID( "pdfSelection" );
var idpage = stringIDToTypeID( "page" );
desc4.putEnumerated( idfsel, idpdfSelection, idpage );
var idPgNm = charIDToTypeID( "PgNm" );
desc4.putInteger( idPgNm, x );
var idCrop = charIDToTypeID( "Crop" );
var idcropTo = stringIDToTypeID( "cropTo" );
var idtrimBox = stringIDToTypeID( "trimBox" );
desc4.putEnumerated( idCrop, idcropTo, idtrimBox );
var idPDFG = charIDToTypeID( "PDFG" );
desc3.putObject( idAs, idPDFG, desc4 );
var idnull = charIDToTypeID( "null" );
desc3.putPath( idnull, new File( theImage ) );
var idFTcs = charIDToTypeID( "FTcs" );
var idQCSt = charIDToTypeID( "QCSt" );
var idQcsa = charIDToTypeID( "Qcsa" );
desc3.putEnumerated( idFTcs, idQCSt, idQcsa );
var idOfst = charIDToTypeID( "Ofst" );
var desc5 = new ActionDescriptor();
var idHrzn = charIDToTypeID( "Hrzn" );
var idRlt = charIDToTypeID( "#Rlt" );
desc5.putUnitDouble( idHrzn, idRlt, 0.000000 );
var idVrtc = charIDToTypeID( "Vrtc" );
var idRlt = charIDToTypeID( "#Rlt" );
desc5.putUnitDouble( idVrtc, idRlt, -0.000000 );
var idOfst = charIDToTypeID( "Ofst" );
desc3.putObject( idOfst, idOfst, desc5 );
var idAntA = charIDToTypeID( "AntA" );
desc3.putBoolean( idAntA, true );
executeAction( idPlc, desc3, DialogModes.NO );
// move forward;
app.activeDocument.activeLayer.move(theLayerSet, ElementPlacement.PLACEATBEGINNING);
return app.activeDocument.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;
};
////// rasterize //////
function rasterize (theLayer) {
app.activeDocument.activeLayer = theLayer;
if (theLayer.kind == LayerKind.SMARTOBJECT) {
// rasterize;
var id631 = charIDToTypeID( "slct" );
var desc125 = new ActionDescriptor();
var id632 = charIDToTypeID( "null" );
var ref83 = new ActionReference();
var id633 = charIDToTypeID( "Mn " );
var id634 = charIDToTypeID( "MnIt" );
var id635 = stringIDToTypeID( "rasterizePlaced" );
ref83.putEnumerated( id633, id634, id635 );
desc125.putReference( id632, ref83 );
executeAction( id631, desc125, DialogModes.NO );
};
return app.activeDocument.activeLayer
};
////// 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 );
}
};
////// 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;
};