• Global community
    • Language:
      • Deutsch
      • English
      • Español
      • Français
      • Português
  • 日本語コミュニティ
    Dedicated community for Japanese speakers
  • 한국 커뮤니티
    Dedicated community for Korean speakers

Align the image layers laterally through the group layer

Engaged ,
Nov 27, 2022 Nov 27, 2022

Copy link to clipboard

Copied

Hello everyone and wonderful forum experts

- Sometimes I divide a number of image layers into groups

- I want a script that will align images sideways, as shown in the attached image

BeforeBeforeAfterAfter

TOPICS
Actions and scripting , SDK

Views

3.1K

Likes

Translate

Translate

Report

Report
Community guidelines
Be kind and respectful, give credit to the original source of content, and search for duplicates before posting. Learn more
community guidelines

correct answers 1 Correct answer

Community Expert , Nov 28, 2022 Nov 28, 2022

@Mohamed Hameed 

 

I am not 100% happy with the following script, however, it has taken longer to get to this point than I expected. I believe that it works as required, let me know how you go.

 

/*
Distribute Grouped Layer Stack Horizontally From Left to Right.jsx
v1.0, 28th November 2022, Stephen Marsh
https://community.adobe.com/t5/photoshop-ecosystem-discussions/align-the-image-layers-laterally-through-the-group-layer/td-p/13375249
*/

#target photoshop

function main() {

    if (activeDocu
...

Likes

Translate

Translate
Community Expert ,
Nov 28, 2022 Nov 28, 2022

Copy link to clipboard

Copied

@Mohamed Hameed 

 

I am not 100% happy with the following script, however, it has taken longer to get to this point than I expected. I believe that it works as required, let me know how you go.

 

/*
Distribute Grouped Layer Stack Horizontally From Left to Right.jsx
v1.0, 28th November 2022, Stephen Marsh
https://community.adobe.com/t5/photoshop-ecosystem-discussions/align-the-image-layers-laterally-through-the-group-layer/td-p/13375249
*/

#target photoshop

function main() {

    if (activeDocument.activeLayer.typename === "LayerSet") {

        var setName = activeDocument.activeLayer.name;
        var count = activeDocument.activeLayer.layers.length;

        activeDocument.activeLayer = activeDocument.layerSets[setName].layers[count - 1];
        var lyrRight = activeDocument.activeLayer.bounds[2].value;

        for (var i = count - 1; i >= 0; i--) {
            selectForwardORBackwardLayer(false, "forwardEnum");
            activeDocument.activeLayer.translate((lyrRight));
            var lyrRight = activeDocument.activeLayer.bounds[2].value;
        }

        // It's a hack, however, it will have to do for now!
        align2SelectAll('AdLf');

        //activeDocument.revealAll();

    } else {
        alert("Please select a layer group containing the layers to distribute from left to right!");
    }
}
activeDocument.suspendHistory("Undo script...", "main()");


// Functions

function selectForwardORBackwardLayer(makeVisible, forwardORbackward) {
    var s2t = function (s) {
        return app.stringIDToTypeID(s);
    };
    var descriptor = new ActionDescriptor();
    var list = new ActionList();
    var reference = new ActionReference();
    // "forwardEnum" or "backwardEnum"
    reference.putEnumerated(s2t("layer"), s2t("ordinal"), s2t(forwardORbackward));
    descriptor.putReference(s2t("null"), reference);
    // true or false
    descriptor.putBoolean(s2t("makeVisible"), makeVisible);
    list.putInteger(15);
    descriptor.putList(s2t("layerID"), list);
    executeAction(s2t("select"), descriptor, DialogModes.NO);
}

function align2SelectAll(method) {
   /* https://gist.github.com/MarshySwamp/df372e342ac87854ffe08e79cbdbcbb5 */
   
    /* 
    AdLf = Align Left
    AdRg = Align Right
    AdCH = Align Centre Horizontal
    AdTp = Align Top
    AdBt = Align Bottom
    AdCV = Align Centre Vertical
    */

    app.activeDocument.selection.selectAll();
    var desc = new ActionDescriptor();
    var ref = new ActionReference();
    ref.putEnumerated(charIDToTypeID("Lyr "), charIDToTypeID("Ordn"), charIDToTypeID("Trgt"));
    desc.putReference(charIDToTypeID("null"), ref);
    desc.putEnumerated(charIDToTypeID("Usng"), charIDToTypeID("ADSt"), charIDToTypeID(method));
    try {
        executeAction(charIDToTypeID("Algn"), desc, DialogModes.NO);
    } catch (e) {}
    app.activeDocument.selection.deselect();
}

 

 

Likes

Translate

Translate

Report

Report
Community guidelines
Be kind and respectful, give credit to the original source of content, and search for duplicates before posting. Learn more
community guidelines
Engaged ,
Nov 28, 2022 Nov 28, 2022

Copy link to clipboard

Copied

@Stephen_A_Marsh 

Thank you very much

I can't find anything I can say to thank you for your amazing effort

I wish you success always and forever

Likes

Translate

Translate

Report

Report
Community guidelines
Be kind and respectful, give credit to the original source of content, and search for duplicates before posting. Learn more
community guidelines
Engaged ,
Nov 28, 2022 Nov 28, 2022

Copy link to clipboard

Copied

@Stephen_A_Marsh 

May I ask a simple query

I would like to add a small modification to the code if possible

I want to align the images inside the group to the left and also to the top before the process of distributing the images
Because sometimes the group contains layers of images in different places

Is this available
If it is not available, you do not have to, this is enough

 

Also, I have a problem that I encounter when the group has a large number of image layers.. When distributing the image layers, some images come out outside the borders of the design
Is there a solution to this problem so that the image layers are distributed within the design or file?

Likes

Translate

Translate

Report

Report
Community guidelines
Be kind and respectful, give credit to the original source of content, and search for duplicates before posting. Learn more
community guidelines
Community Expert ,
Nov 28, 2022 Nov 28, 2022

Copy link to clipboard

Copied

quote

@Stephen_A_Marsh 

May I ask a simple query

I would like to add a small modification to the code if possible

I want to align the images inside the group to the left and also to the top before the process of distributing the images
Because sometimes the group contains layers of images in different places

Is this available
If it is not available, you do not have to, this is enough


By @Mohamed Hameed

 

I'll see what I can do, however, I have to say that this script is proving to be challenging for me! :]

 

 

quote

Also, I have a problem that I encounter when the group has a large number of image layers.. When distributing the image layers, some images come out outside the borders of the design
Is there a solution to this problem so that the image layers are distributed within the design or file?

 

That was clearly marked in your original screenshots, the right-hand edge of the group content extended past the canvas.

 

Offhand, you have two choices:

 

1) Make the canvas larger (I have placeholder code in there commented out to reveal all)

 

2) Scale the group smaller

 

Likes

Translate

Translate

Report

Report
Community guidelines
Be kind and respectful, give credit to the original source of content, and search for duplicates before posting. Learn more
community guidelines
Engaged ,
Nov 28, 2022 Nov 28, 2022

Copy link to clipboard

Copied

@Stephen_A_Marsh 

Very thankful for your interest
Indeed, I enlarged the file size .. But what is the work if the group contains more than 30 or 40 image layers, the width of the file will be very large

Overall, thanks for your interest
I would be very grateful if a solution could be reached

I found a plugin in one of the sites that distributes the image layers inside the rectangle marquee, but the problem with this plugin does not work on some old versions, but only on modern versions

Likes

Translate

Translate

Report

Report
Community guidelines
Be kind and respectful, give credit to the original source of content, and search for duplicates before posting. Learn more
community guidelines
Community Expert ,
Nov 30, 2022 Nov 30, 2022

Copy link to clipboard

Copied

A while back I tried to automate filling an area with lines of images (with as little repition as possible). 

Screenshot 2022-11-30 at 16.58.14.pngScreenshot 2022-11-30 at 16.58.23.png

// arranges the selected jpg, tif, psd  and pdf in lines of the same height within the bounds of a selection or a set boundary within the file;
// gutters may be irregular due to rounding effects;
// 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 mac and 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 = [0, 0, myDocument.width, myDocument.height]};
if ( theArray[2] - theArray[0] > 100 && theArray[3] - theArray[1] > 100) {
// 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 files", getFiles, true)};	
// do the arrangement
	if (theFiles) {placeInLines (myDocument, theFiles, theArray)}
	}
else {alert ("file too small")};
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) {
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";
// add a white fill layer;
var aFill = makeFillLayer ("white", 0, 0, 0, 0);
aFill.move (theGroup, ElementPlacement.PLACEATBEGINNING);
// 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");
				var repeat = true;
				};
			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;
};
////// the fill-layer-function //////
function makeFillLayer (a, b, c, d, e) {
var idMk = charIDToTypeID( "Mk  " );
    var desc6 = new ActionDescriptor();
    var idnull = charIDToTypeID( "null" );
        var ref2 = new ActionReference();
        var idcontentLayer = stringIDToTypeID( "contentLayer" );
        ref2.putClass( idcontentLayer );
    desc6.putReference( idnull, ref2 );
    var idUsng = charIDToTypeID( "Usng" );
        var desc7 = new ActionDescriptor();
        var idNm = charIDToTypeID( "Nm  " );
        desc7.putString( idNm, a );
        var idType = charIDToTypeID( "Type" );
            var desc8 = new ActionDescriptor();
            var idClr = charIDToTypeID( "Clr " );
                var desc9 = new ActionDescriptor();
                var idCyn = charIDToTypeID( "Cyn " );
                desc9.putDouble( idCyn, b );
                var idMgnt = charIDToTypeID( "Mgnt" );
                desc9.putDouble( idMgnt, c );
                var idYlw = charIDToTypeID( "Ylw " );
                desc9.putDouble( idYlw, d );
                var idBlck = charIDToTypeID( "Blck" );
                desc9.putDouble( idBlck, e );
            var idCMYC = charIDToTypeID( "CMYC" );
            desc8.putObject( idClr, idCMYC, desc9 );
        var idsolidColorLayer = stringIDToTypeID( "solidColorLayer" );
        desc7.putObject( idType, idsolidColorLayer, desc8 );
    var idcontentLayer = stringIDToTypeID( "contentLayer" );
    desc6.putObject( idUsng, idcontentLayer, desc7 );
executeAction( idMk, desc6, DialogModes.NO );
return app.activeDocument.activeLayer
};

 

Likes

Translate

Translate

Report

Report
Community guidelines
Be kind and respectful, give credit to the original source of content, and search for duplicates before posting. Learn more
community guidelines
Engaged ,
Nov 30, 2022 Nov 30, 2022

Copy link to clipboard

Copied

@c.pfaffenbichler 

First, I am very, very thankful for your great effort, and this code actually works on any files and works on distributing them well

But I encountered a problem where the image layers are duplicated, which I do not want

Here I attached a folder containing a number of images, which are 14 images, but when distributing them through the script, some of the images were repeated

I don't know where exactly the problem is

 

- I also noticed that after distributing the image layers in the first row and moving to the other rows, there was no alignment to arrange the layers, as shown in red in the last image.

 

 

 

Pictures inside the folderPictures inside the folderimage layersimage layersDistribution in the final form within a selectionDistribution in the final form within a selection

 

there was no alignment to arrange the layers, as shown in red in the last image.there was no alignment to arrange the layers, as shown in red in the last image.

Likes

Translate

Translate

Report

Report
Community guidelines
Be kind and respectful, give credit to the original source of content, and search for duplicates before posting. Learn more
community guidelines
Community Expert ,
Nov 30, 2022 Nov 30, 2022

Copy link to clipboard

Copied

Yes, that code »clips« the image at the end of a line and »continues« it in the next line and, in order to fill the area completely, starts from the first image again. 

Likes

Translate

Translate

Report

Report
Community guidelines
Be kind and respectful, give credit to the original source of content, and search for duplicates before posting. Learn more
community guidelines
Engaged ,
Nov 30, 2022 Nov 30, 2022

Copy link to clipboard

Copied

@c.pfaffenbichler 

Is it possible to modify the code to prevent duplication of images

Only works on selected images without duplication

Likes

Translate

Translate

Report

Report
Community guidelines
Be kind and respectful, give credit to the original source of content, and search for duplicates before posting. Learn more
community guidelines
Community Expert ,
Nov 30, 2022 Nov 30, 2022

Copy link to clipboard

Copied

You can remove the lines 

			if (repeat == false) {
//var repeat = confirm("repeat images to fill format?", false, "repeat");
				var repeat = true;
				};
			if (repeat == true) {theNumber = 0}

Likes

Translate

Translate

Report

Report
Community guidelines
Be kind and respectful, give credit to the original source of content, and search for duplicates before posting. Learn more
community guidelines
Engaged ,
Dec 01, 2022 Dec 01, 2022

Copy link to clipboard

Copied

@c.pfaffenbichler 

I already deleted the lines and the problem is still there

111.jpg112.jpg

Likes

Translate

Translate

Report

Report
Community guidelines
Be kind and respectful, give credit to the original source of content, and search for duplicates before posting. Learn more
community guidelines
Engaged ,
Dec 01, 2022 Dec 01, 2022

Copy link to clipboard

Copied

@c.pfaffenbichler 

I made a simple modification and deleted the lines for the repetition process and the problem was solved in a simple way, but the repetition is still there

101.jpg100.jpg

 

I want to make the code content only with the selected images
And not to repeat other lines with the same pictures

Likes

Translate

Translate

Report

Report
Community guidelines
Be kind and respectful, give credit to the original source of content, and search for duplicates before posting. Learn more
community guidelines
Community Expert ,
Dec 01, 2022 Dec 01, 2022

Copy link to clipboard

Copied

Did you also remove the lines 

			if (repeat == false) {
//var repeat = confirm("repeat images to fill format?", false, "repeat");
				var repeat = true;
				};
			if (repeat == true) {theNumber = 0}

in this version? 

Likes

Translate

Translate

Report

Report
Community guidelines
Be kind and respectful, give credit to the original source of content, and search for duplicates before posting. Learn more
community guidelines
Engaged ,
Dec 01, 2022 Dec 01, 2022

Copy link to clipboard

Copied

@c.pfaffenbichler 

The problem was solved when I modified this part of the code

But I see that the implementation of the procedure may be relatively slow, but the code is working fine now

Thank you very much for your effort

200.jpg201.jpg

Likes

Translate

Translate

Report

Report
Community guidelines
Be kind and respectful, give credit to the original source of content, and search for duplicates before posting. Learn more
community guidelines
Community Expert ,
Dec 01, 2022 Dec 01, 2022

Copy link to clipboard

Copied

LATEST

But I see that the implementation of the procedure may be relatively slow, but the code is working fine now

It was code that I worked on more than ten years ago, so I suspect it could indeed be sped up considerably … 

The whole pdf-related work-around could probably be dumped, though that is probably not the main »drag«. 

Likes

Translate

Translate

Report

Report
Community guidelines
Be kind and respectful, give credit to the original source of content, and search for duplicates before posting. Learn more
community guidelines
Engaged ,
Dec 01, 2022 Dec 01, 2022

Copy link to clipboard

Copied

quote

Did you also remove the lines 

 

			if (repeat == false) {
//var repeat = confirm("repeat images to fill format?", false, "repeat");
				var repeat = true;
				};
			if (repeat == true) {theNumber = 0}

 

in this version? 


By @c.pfaffenbichler

I already deleted the code and it was fine too
Thank you very very much
How great and brilliant you are

Likes

Translate

Translate

Report

Report
Community guidelines
Be kind and respectful, give credit to the original source of content, and search for duplicates before posting. Learn more
community guidelines