Search code examples
photoshopphotoshop-script

Adobe Photoshop Scripting - How to Select Bounding Box Around Current Selection?


Does anyone know whether it's possible, in Photoshop extend script, to convert an irregular selection (e.g. magic wand tool selection) into a rectangular selection encompassing the top, left, bottom and right bounds of the selection?


Solution

  • Here it is, I have documented the code so you can modify it later if you need. Also, check page 166 and following of Photoshop's JS reference manual, you may read more about selections - you can set feather, extend/intersect/etc. the selection if you need to.

    Made for CS6, should work with latter.

    #target photoshop
    if (documents.length == 0) {
        alert("nothing opened");
    } else {
        // start
    
        //setup
        var file = app.activeDocument;
        var selec =  file.selection; 
    
        //run
        var bnds = selec.bounds; // get the bounds of current selection
        var // save the particular pixel values
           xLeft = bnds[0],
           yTop = bnds[1],
           xRight = bnds[2],
           yBottom = bnds[3];
    
        var newRect = [ [xLeft,yTop], [xLeft,yBottom], [xRight,yBottom], [xRight,yTop] ]; // set coords for selection, counter-clockwise
    
        selec.deselect;
        selec.select(newRect);
    
        // end
    }