Search code examples
javascriptjsxphotoshop-script

Script auto make selection snap to added guides line


I need a script for photoshop which can create a square or rectangular selection (use rectangular marquee tool) and it will snap to the guides line, no matter the position of the guides, sometimes with 2 guides sometimes I will add 4 guides. Or it'll be ok if the script make a selection from the guide to the bottom of the photo.

make selection snap to guides

Here are some other options that I'm expecting make selection 1 make selection 2


Solution

  • Here script that creates a rectangular selection:

    // Get the active document
    var doc = app.activeDocument;
    
    // Get the guides
    var guides = doc.guides;
    
    // Get the first horizontal and vertical guides
    var hGuide1 = guides[0];
    var vGuide1 = guides[1];
    
    // Get the second horizontal and vertical guides (if they exist)
    var hGuide2 = guides.length > 2 ? guides[2] : null;
    var vGuide2 = guides.length > 3 ? guides[3] : null;
    
    // Calculate the selection coordinates based on the guides
    var x1 = vGuide1.direction == Direction.VERTICAL ? vGuide1.coordinate : hGuide1.coordinate;
    var y1 = hGuide1.direction == Direction.HORIZONTAL ? hGuide1.coordinate : vGuide1.coordinate;
    var x2 = vGuide2 != null && vGuide2.direction == Direction.VERTICAL ? vGuide2.coordinate : doc.width.as("px");
    var y2 = hGuide2 != null && hGuide2.direction == Direction.HORIZONTAL ? hGuide2.coordinate : doc.height.as("px");
    
    // Create the rectangular selection
    doc.selection.select([[x1, y1], [x2, y1], [x2, y2], [x1, y2]], SelectionType.REPLACE, 0, false);
    

    To run it, create a file with the extension jsx. For example: script.jsx

    Then File->Scripts->Browse... select the file script.jsx