Selection boundaries and image bottom do not return values

Hello everyone!

I’m trying to create an automatic crop, but I can’t find the distance in pixels between the selection and the bottom edge. This is the code I found to get the values.

All the values ​​return exact, but the (bottom) doesn’t return anything.

   const app = require('photoshop').app;
    const core = require('photoshop').core;

    await core.executeAsModal(async () => {
        const result = await require('photoshop').action.batchPlay(
            [
                {
                    _obj: 'get',
                    _target: [{ _property: 'selection' }, { _ref: 'document', _enum: 'ordinal', _value: 'targetEnum' }]
                }
            ],
            { synchronousExecution: true }
        );

        if (result.length > 0 && result[0].selection) {
            // Extraindo valores corretamente
            const bounds = result[0].selection;
            const left = bounds.left._value || 0;
            const top = bounds.top._value || 0;
            const right = bounds.right._value || 0;
            const bottom = bounds.bottom._value || 0;

            const docWidth = app.activeDocument.width;
            const docHeight = app.activeDocument.height;

            // Calculando distâncias até as bordas
            const distancia = {
                esquerda: left, 
                topo: top, 
                direita: docWidth - right, 
                baixo: docHeight - bottom 
            };

            alert(`Distância da seleção até as bordas:\n
                   Esquerda: ${distancia.esquerda}px\n
                   Topo: ${distancia.topo}px\n
                   Direita: ${distancia.direita}px\n
                   Baixo: ${distancia.baixo}px`);
        } else {
            alert('Nenhuma seleção ativa encontrada.');
        }
    });

Does this not work for you?

const app = require("photoshop").app;

// Check for an active document
const doc = app.activeDocument;
if (!doc) {
    app.showAlert("No active documents.");
    return;
}

// Check for an active selection
const sel = doc.selection;
if (!sel.bounds) {
    app.showAlert("No active selection.");
    return;
}

// Calculando distâncias até as bordas
const distancia = {
    esquerda: sel.bounds.left,
    topo: sel.bounds.top,
    direita: doc.width - sel.bounds.right,
    baixo: doc.height - sel.bounds.bottom,
};

app.showAlert(`Distância da seleção até as bordas:
Esquerda: ${distancia.esquerda}px
Topo: ${distancia.topo}px
Direita: ${distancia.direita}px
Baixo: ${distancia.baixo}px`);
1 Like

jduncan thank you very much! It worked perfectly. I spent the night looking for a way to get these speakers and now I see that my code was on the wrong path or very messed up. Once again I thank you for your kindness.

1 Like

Glad to hear that worked for you. My pleasure!

1 Like