Skip to main content
Inspiring
December 6, 2024
Answered

Script for the absolute value of a text box middle value

  • December 6, 2024
  • 4 replies
  • 2895 views

Hi community. 

 

can someone please share a script which I can select all the text in my file, and it will display only the middle X value? 

 

I already do have 2-3 other scripts which display the X & Y Locations of a bouding box of each object. Once i run the script the values are output into a notepad on my desktop which is super helpful. But now if Possible I just need the script to show the X value of the bounding box.

 

 

This topic has been closed for replies.
Correct answer r-bin

My bad, I thought the Script code was posted. here's what I have so far:

function get_text_mid_x_y(idx) {
try {
function transform(p, xx, xy, yx, yy, tx, ty) {
var x = p[0];
var y = p[1];
p[0] = xx * x + yx * y + tx;
p[1] = xy * x + yy * y + ty;
}

var doc = app.activeDocument;

var old_units = app.preferences.rulerUnits;
app.preferences.rulerUnits = Units.PIXELS;

var w = doc.width.value;
var h = doc.height.value;

app.preferences.rulerUnits = old_units;

var r = new ActionReference();
r.putProperty(stringIDToTypeID("property"), stringIDToTypeID("textKey"));

if (idx >= 1) {
r.putIndex(stringIDToTypeID("layer"), idx);
} else {
r.putEnumerated(stringIDToTypeID("layer"), stringIDToTypeID("ordinal"), stringIDToTypeID("targetEnum"));
}

var tkey = executeActionGet(r).getObjectValue(stringIDToTypeID("textKey"));

var xx = 1, xy = 0, yx = 0, yy = 1, tx = 0, ty = 0;

if (tkey.hasKey(stringIDToTypeID("transform"))) {
xx = tkey.getObjectValue(stringIDToTypeID("transform")).getDouble(stringIDToTypeID("xx"));
xy = tkey.getObjectValue(stringIDToTypeID("transform")).getDouble(stringIDToTypeID("xy"));
yx = tkey.getObjectValue(stringIDToTypeID("transform")).getDouble(stringIDToTypeID("yx"));
yy = tkey.getObjectValue(stringIDToTypeID("transform")).getDouble(stringIDToTypeID("yy"));
tx = tkey.getObjectValue(stringIDToTypeID("transform")).getDouble(stringIDToTypeID("tx"));
ty = tkey.getObjectValue(stringIDToTypeID("transform")).getDouble(stringIDToTypeID("ty"));
}

var x0 = tkey.getObjectValue(stringIDToTypeID("bounds")).getUnitDoubleValue(stringIDToTypeID("left"));
var y0 = tkey.getObjectValue(stringIDToTypeID("bounds")).getUnitDoubleValue(stringIDToTypeID("top"));
var x1 = tkey.getObjectValue(stringIDToTypeID("bounds")).getUnitDoubleValue(stringIDToTypeID("right"));
var y1 = tkey.getObjectValue(stringIDToTypeID("bounds")).getUnitDoubleValue(stringIDToTypeID("bottom"));

var p1 = [[x0, y0], [x1, y0], [x1, y1], [x0, y1]];

var ch = tkey.getObjectValue(stringIDToTypeID("textClickPoint")).getUnitDoubleValue(stringIDToTypeID("horizontal"));
var cv = tkey.getObjectValue(stringIDToTypeID("textClickPoint")).getUnitDoubleValue(stringIDToTypeID("vertical"));

tx += w * ch / 100;
ty += h * cv / 100;

transform(p1[0], xx, xy, yx, yy, tx, ty);
transform(p1[1], xx, xy, yx, yy, tx, ty);
transform(p1[2], xx, xy, yx, yy, tx, ty);
transform(p1[3], xx, xy, yx, yy, tx, ty);

var l = Math.min(p1[0][0], p1[1][0], p1[2][0], p1[3][0]);
var r = Math.max(p1[0][0], p1[1][0], p1[2][0], p1[3][0]);
var t = Math.min(p1[0][1], p1[1][1], p1[2][1], p1[3][1]);
var b = Math.max(p1[0][1], p1[1][1], p1[2][1], p1[3][1]);

var mid_x = (l + r) / 2;
var mid_y = (t + b) / 2;

return [mid_x, mid_y];
} catch (e) {
alert("Error in get_text_mid_x_y: " + e.message);
}
}

function processSelectedLayers() {
try {
var doc = app.activeDocument;

// Open file to save results
var desktop = Folder.desktop;
var file = new File(desktop + "/LayerMidXValues.txt");
file.open("w");

// Get active layers
var ref = new ActionReference();
ref.putProperty(stringIDToTypeID("property"), stringIDToTypeID("targetLayers"));
ref.putEnumerated(stringIDToTypeID("document"), stringIDToTypeID("ordinal"), stringIDToTypeID("targetEnum"));
var list = executeActionGet(ref).getList(stringIDToTypeID("targetLayers"));

for (var i = 0; i < list.count; i++) {
var layerIndex = list.getReference(i).getIndex();
var layer = doc.layers[layerIndex - 1];
var layerName = layer.name;

// Get mid X and Y
var mid = get_text_mid_x_y(layerIndex);

// Save to file
file.writeln("Layer Name: " + layerName);
file.writeln("Mid X: " + mid[0].toFixed(2));
file.writeln("Mid Y: " + mid[1].toFixed(2));
file.writeln("-----------------------");

// Show alerts for verification
alert("Layer: " + layerName + "\nMid X: " + mid[0].toFixed(2) + "\nMid Y: " + mid[1].toFixed(2));
}

// Close file
file.close();
alert("Results saved to LayerMidXValues.txt on desktop.");
} catch (e) {
alert("Error in processSelectedLayers: " + e.message);
}
}

// Run the script
processSelectedLayers();


Did you write this code yourself or did GPT do it?
There is incorrect work with layers and their indexes, that's why there is confusion.
Check this code
 

 

////////////////////////////////////////////////////////
function get_selected_layers_idx()
    {
    try {
        var r = new ActionReference();
        r.putProperty(stringIDToTypeID("property"), stringIDToTypeID("targetLayers"));
        r.putEnumerated(stringIDToTypeID("document"), stringIDToTypeID("ordinal"), stringIDToTypeID("targetEnum"));

        try {
            var list = executeActionGet(r).getList(stringIDToTypeID("targetLayers"));
            }
        catch (e) 
            { 
            var r = new ActionReference();
            r.putProperty(stringIDToTypeID("property"), stringIDToTypeID("itemIndex"));
            r.putEnumerated(stringIDToTypeID("layer"), stringIDToTypeID("ordinal"), stringIDToTypeID("targetEnum"));
            return [ executeActionGet(r).getInteger(stringIDToTypeID("itemIndex"))-1 ];
            }

        var selected_layers = new Array();

        for (var i = 0; i < list.count; i++) selected_layers.push(list.getReference(i).getIndex());

        return selected_layers;
        }

    catch (e) { alert(e.message +"\nline:"+e.line); }
    }

////////////////////////////////////////////////////////
function get_layer_info(idx) 
    {
    try {
        function transform(p, xx, xy, yx, yy, tx, ty) 
            {
            var x = p[0];
            var y = p[1];
            p[0] = xx * x + yx * y + tx;
            p[1] = xy * x + yy * y + ty;
            }

        var doc = app.activeDocument;

        var old_units = app.preferences.rulerUnits;
        app.preferences.rulerUnits = Units.PIXELS;

        var w = doc.width.value;
        var h = doc.height.value;

        app.preferences.rulerUnits = old_units;

        var r = new ActionReference();
        r.putProperty(stringIDToTypeID("property"), stringIDToTypeID("textKey"));
        r.putIndex(stringIDToTypeID("layer"), idx);

        var tkey = executeActionGet(r).getObjectValue(stringIDToTypeID("textKey"));

        var xx = 1, xy = 0, yx = 0, yy = 1, tx = 0, ty = 0;

        if (tkey.hasKey(stringIDToTypeID("transform"))) 
            {
            xx = tkey.getObjectValue(stringIDToTypeID("transform")).getDouble(stringIDToTypeID("xx"));
            xy = tkey.getObjectValue(stringIDToTypeID("transform")).getDouble(stringIDToTypeID("xy"));
            yx = tkey.getObjectValue(stringIDToTypeID("transform")).getDouble(stringIDToTypeID("yx"));
            yy = tkey.getObjectValue(stringIDToTypeID("transform")).getDouble(stringIDToTypeID("yy"));
            tx = tkey.getObjectValue(stringIDToTypeID("transform")).getDouble(stringIDToTypeID("tx"));
            ty = tkey.getObjectValue(stringIDToTypeID("transform")).getDouble(stringIDToTypeID("ty"));
            }

        var x0 = tkey.getObjectValue(stringIDToTypeID("bounds")).getUnitDoubleValue(stringIDToTypeID("left"));
        var y0 = tkey.getObjectValue(stringIDToTypeID("bounds")).getUnitDoubleValue(stringIDToTypeID("top"));
        var x1 = tkey.getObjectValue(stringIDToTypeID("bounds")).getUnitDoubleValue(stringIDToTypeID("right"));
        var y1 = tkey.getObjectValue(stringIDToTypeID("bounds")).getUnitDoubleValue(stringIDToTypeID("bottom"));

        var p1 = [[x0, y0], [x1, y0], [x1, y1], [x0, y1]];

        var ch = tkey.getObjectValue(stringIDToTypeID("textClickPoint")).getUnitDoubleValue(stringIDToTypeID("horizontal"));
        var cv = tkey.getObjectValue(stringIDToTypeID("textClickPoint")).getUnitDoubleValue(stringIDToTypeID("vertical"));

        tx += w * ch / 100;
        ty += h * cv / 100;

        transform(p1[0], xx, xy, yx, yy, tx, ty);
        transform(p1[1], xx, xy, yx, yy, tx, ty);
        transform(p1[2], xx, xy, yx, yy, tx, ty);
        transform(p1[3], xx, xy, yx, yy, tx, ty);

        var l = Math.min(p1[0][0], p1[1][0], p1[2][0], p1[3][0]);
        var r = Math.max(p1[0][0], p1[1][0], p1[2][0], p1[3][0]);
        var t = Math.min(p1[0][1], p1[1][1], p1[2][1], p1[3][1]);
        var b = Math.max(p1[0][1], p1[1][1], p1[2][1], p1[3][1]);

        var mid_x = (l + r) / 2;
        var mid_y = (t + b) / 2;

        var r = new ActionReference();
        r.putProperty(stringIDToTypeID("property"), stringIDToTypeID("name"));
        r.putIndex(stringIDToTypeID("layer"), idx);
                              
        return [executeActionGet(r).getString(stringIDToTypeID("name")), mid_x, mid_y];
        } 
    catch (e) 
        {
        alert("Error in get_layer_info: " + e.message +"\nline:"+e.line);
        }
    }

////////////////////////////////////////////////////////
function processSelectedLayers() 
    {
    try {
        var doc = app.activeDocument;

        // Open file to save results
        var desktop = Folder.desktop;
        var file = new File(desktop + "/LayerMidXValues.txt");
        file.open("w");

        // Get active layers

        var idx = get_selected_layers_idx();

        var n = 0;
        try { activeDocument.backgroundLayer } catch (e) { n = 1; }

        for (var i = 0; i < idx.length; i++) 
            {
            var info = get_layer_info(idx[i]+n);

            // Save to file
            file.writeln("Layer Name: " + info[0]);
            file.writeln("Mid X: " + info[1].toFixed(2));
            file.writeln("Mid Y: " + info[2].toFixed(2));
            file.writeln("-----------------------");

            // Show alerts for verification
            alert("Layer: " + info[0] + "\nMid X: " + info[1].toFixed(2) + "\nMid Y: " + info[2].toFixed(2));
            }

            // Close file
            file.close();
            alert("Results saved to LayerMidXValues.txt on desktop.");
        } 
    catch (e) 
        {
        alert("Error in processSelectedLayers: " + e.message +"\nline:"+e.line);
        }
    }

////////////////////////////////////////////////////////
// Run the script
processSelectedLayers();

 

4 replies

c.pfaffenbichler
Community Expert
Community Expert
December 6, 2024

Are the Type Layers Point Text or Paragraph Text? 

Inspiring
December 6, 2024

It was point text. 

 

Kind regards.

c.pfaffenbichler
Community Expert
Community Expert
December 6, 2024

Will you ever provide the file for testing? 

 

Anyway … please try this: 

 

// type layer properties;
// based on code by michael l hale;
// 2024, use it at your own risk;
if (app.documents.length > 0) {
// set to pixels;
var originalRulerUnits = app.preferences.rulerUnits;
app.preferences.rulerUnits = Units.PIXELS;
var myDocument = activeDocument;
var theWidth = myDocument.width;
var theHeight = myDocument.height; 
// get values;
var ref = new ActionReference();
ref.putProperty(stringIDToTypeID("property"), stringIDToTypeID('textKey'));
ref.putEnumerated( charIDToTypeID("Lyr "), charIDToTypeID("Ordn"), charIDToTypeID("Trgt") ); 
var layerDesc = executeActionGet(ref);
if (layerDesc.hasKey(stringIDToTypeID('textKey')) == true) {
var textDesc = layerDesc.getObjectValue(stringIDToTypeID('textKey'));
var thePoint = textDesc.getObjectValue(stringIDToTypeID("textClickPoint"));
var theHor = thePoint.getUnitDoubleValue(stringIDToTypeID("horizontal"));
var theVer = thePoint.getUnitDoubleValue(stringIDToTypeID("vertical"));
alert (Number(theHor)*Number(theWidth)/100+"___"+Number(theVer)*Number(theHeight)/100);
// reset;
app.preferences.rulerUnits = originalRulerUnits;
}
};

edited

 

 

Stephen Marsh
Community Expert
Community Expert
December 6, 2024

@Stefan Cargoski 

 

Try this (please use the </> control to paste code next time as the standard forum formatting can break the code):

 

// 2024 modified for middle center, use it at your own risk;

#target photoshop

if (app.documents.length > 0) {

    var theLayers = collectSelectedLayersBounds();
    alert(theLayers.join("\n"));
    // copy text to clipboard
    var d = new ActionDescriptor();
    d.putString(stringIDToTypeID("textData"), theLayers.join("\n"));
    executeAction(stringIDToTypeID("textToClipboard"), d, DialogModes.NO);
    // write text to file
    var txt = theLayers.join("\n");
    var textFile = new File('~/Desktop' + '/' + 'layerList.txt');
    textFile.open('w');
    textFile.encoding = 'UTF-8';
    textFile.write(txt);
    textFile.close();

}

////// collect bounds of selected layers //////
function collectSelectedLayersBounds() {

    // set to pixels;
    var originalRulerUnits = app.preferences.rulerUnits;
    app.preferences.rulerUnits = Units.PIXELS;

    // get selected layers;
    var selectedLayers = [];
    var ref = new ActionReference();
    ref.putEnumerated(charIDToTypeID("Dcmn"), charIDToTypeID("Ordn"), charIDToTypeID("Trgt"));
    var desc = executeActionGet(ref);
    if (desc.hasKey(stringIDToTypeID('targetLayers'))) {

        desc = desc.getList(stringIDToTypeID('targetLayers'));
        var c = desc.count;

        // run through selected layers;
        for (var i = 0; i < c; i++) {
            try {
                activeDocument.backgroundLayer;
                var theIndex = desc.getReference(i).getIndex();
            } catch (e) { var theIndex = desc.getReference(i).getIndex() + 1 };
            
            // get id for solid color layers;
            try {
                var ref = new ActionReference();
                ref.putIndex(charIDToTypeID("Lyr "), theIndex);
                var layerDesc = executeActionGet(ref);
                var theName = layerDesc.getString(stringIDToTypeID('name'));
                var theBounds = layerDesc.getObjectValue(stringIDToTypeID("bounds"));

                var left = theBounds.getUnitDoubleValue(stringIDToTypeID("left"));
                var top = theBounds.getUnitDoubleValue(stringIDToTypeID("top"));
                var right = theBounds.getUnitDoubleValue(stringIDToTypeID("right"));
                var bottom = theBounds.getUnitDoubleValue(stringIDToTypeID("bottom"));

                var centerX = (left + right) / 2;
                var centerY = (top + bottom) / 2;

                selectedLayers.push([theName, [centerX, centerY]]);
            } catch (e) { }
        }

    // if only one:
    } else {
        var ref = new ActionReference();
        ref.putEnumerated(charIDToTypeID("Lyr "), charIDToTypeID("Ordn"), charIDToTypeID("Trgt"));
        var layerDesc = executeActionGet(ref);
        try {
            var theName = layerDesc.getString(stringIDToTypeID('name'));
            var theBounds = layerDesc.getObjectValue(stringIDToTypeID("bounds"));

            var left = theBounds.getUnitDoubleValue(stringIDToTypeID("left"));
            var top = theBounds.getUnitDoubleValue(stringIDToTypeID("top"));
            var right = theBounds.getUnitDoubleValue(stringIDToTypeID("right"));
            var bottom = theBounds.getUnitDoubleValue(stringIDToTypeID("bottom"));

            var centerX = (left + right) / 2;
            var centerY = (top + bottom) / 2;

            selectedLayers = [[theName, [centerX, centerY]]];
        } catch (e) { }
    }

    // reset;
    app.preferences.rulerUnits = originalRulerUnits;
    return selectedLayers;

}
Inspiring
December 6, 2024

unfortnately it didnt work to register the X value. Im still getting the registration of the top left corner.
The Script should have the X value of= 175

Stephen Marsh
Community Expert
Community Expert
December 6, 2024

Hmm, it all worked fine for me, I tested on a text layer and a raster layer.

 

@c.pfaffenbichler – sorry to intrude, but this looks like your original code. Do you have any insights?

Stephen Marsh
Community Expert
Community Expert
December 6, 2024

@Stefan Cargoski 

 

It would be helpful if you posted the other scripts so that the appropriate modifications can be made to the unknown variables such as ruler units, text file location etc. Here is something more generic...

 

var selectionBounds = app.activeDocument.selection.bounds;
var selectionLeft = selectionBounds[0].value;
var selectionTop = selectionBounds[1].value;
var selectionRight = selectionBounds[2].value;
var selectionBottom = selectionBounds[3].value;
var selectionWidth = selectionBounds[2].value - selectionBounds[0].value;
var selectionHeight = selectionBounds[3].value - selectionBounds[1].value;
var selectionXCenter = (selectionLeft) + (selectionWidth / 2);
var selectionYCenter = (selectionTop) + (selectionHeight / 2);
alert(selectionXCenter + ", " + selectionYCenter);

 

 

Inspiring
December 6, 2024

Sure here is the latest script I've been using:

// 2020, use it at your own risk;
#target photoshop
if (app.documents.length > 0) {
var theLayers = collectSelectedLayersBounds ();
alert(theLayers.join("\n"));
// copy text to clipboard
var d = new ActionDescriptor();
d.putString(stringIDToTypeID("textData"), theLayers.join("\n"));
executeAction(stringIDToTypeID("textToClipboard"), d, DialogModes.NO);
// write text to file
var txt = theLayers.join("\n");
var textFile = new File('~/Desktop' + '/' + 'layerList.txt');
textFile.open('w');
textFile.encoding = 'UTF-8';
textFile.write(txt);
textFile.close();
}
////// collect bounds of selected layers //////
function collectSelectedLayersBounds () {
// set to pixels;
var originalRulerUnits = app.preferences.rulerUnits;
app.preferences.rulerUnits = Units.PIXELS;
// get selected layers;
var selectedLayers = [];
var ref = new ActionReference();
ref.putEnumerated( charIDToTypeID("Dcmn"), charIDToTypeID("Ordn"), charIDToTypeID("Trgt") );
var desc = executeActionGet(ref);
if( desc.hasKey( stringIDToTypeID( 'targetLayers' ) ) ){
desc = desc.getList( stringIDToTypeID( 'targetLayers' ));
var c = desc.count;
// run through selected layers;
for(var i=0;i<c;i++){
try{activeDocument.backgroundLayer;
var theIndex = desc.getReference( i ).getIndex();
}catch(e){var theIndex = desc.getReference( i ).getIndex()+1 };
// get id for solid color layers;
try {
var ref = new ActionReference();
ref.putIndex( charIDToTypeID("Lyr "), theIndex );
var layerDesc = executeActionGet(ref);
var theName = layerDesc.getString(stringIDToTypeID('name'));
var theBounds = layerDesc.getObjectValue(stringIDToTypeID("bounds"));
var theseBounds = [theBounds.getUnitDoubleValue(stringIDToTypeID("left")), theBounds.getUnitDoubleValue(stringIDToTypeID("top"))];
selectedLayers.push([theName, theseBounds]);
} catch (e) {}
}
// if only one:
}else{
var ref = new ActionReference();
ref.putEnumerated( charIDToTypeID("Lyr "), charIDToTypeID("Ordn"), charIDToTypeID("Trgt") );
var layerDesc = executeActionGet(ref);
try {
var theName = layerDesc.getString(stringIDToTypeID('name'));
var theBounds = layerDesc.getObjectValue(stringIDToTypeID("bounds"));
var theseBounds = [theBounds.getUnitDoubleValue(stringIDToTypeID("left")), theBounds.getUnitDoubleValue(stringIDToTypeID("top"))];
selectedLayers = [[theName, theseBounds]];
} catch (e) {}
}
// reset;
app.preferences.rulerUnits = originalRulerUnits;
return selectedLayers;
}