Skip to main content
Known Participant
March 27, 2024
Answered

How to draw an irregular selection into a rectangular selection?

  • March 27, 2024
  • 4 replies
  • 860 views

I want to draw an irregular selection into a new rectangular selection using the Photoshop rectangular marquee tool, as shown in the picture. I hope to get everyone's help. Thank you very much.

Desired                                                                        Original

This topic has been closed for replies.
Correct answer c.pfaffenbichler

// create rectangular sub selections for irregular ones;
// 2024, use it at your own risk;
if (app.documents.length > 0) {
if (hasSelection() == true) {
// set to pixels;
var originalRulerUnits = app.preferences.rulerUnits;
app.preferences.rulerUnits = Units.PIXELS;
////////////////////////////////////
saveSelectionToNewFile ();
var myDocument = app.activeDocument;
var myLayer = myDocument.activeLayer;
myLayer.threshold(1);
myDocument.resizeImage(new UnitValue (200, "%"), new UnitValue (200, "%"), undefined, ResampleMethod.NEARESTNEIGHBOR);
myDocument.selection.load(myDocument.channels[0], SelectionType.REPLACE);
var thePath = makeWorkPath(0);
myDocument.resizeImage(new UnitValue (50, "%"), new UnitValue (50, "%"), undefined, ResampleMethod.NEARESTNEIGHBOR);
var thePathArray = collectPathInfoFromDesc2023 (myDocument, thePath);
myDocument.close(SaveOptions.DONOTSAVECHANGES);
////////////////////////////////////
var theResults = new Array;
var theAdd = false;
for (var m = 0; m < thePathArray.length; m++) {
    var thisOne = thePathArray[m];
    var thisArray = new Array;
    for (var n = 0; n < thisOne.length-2; n++) {
        thisArray.push(thisOne[n][0])
    };
    var theIndex = 0;
    thisArray.sort(sortArrayByIndexedItem);
    var x1 = thisArray[0][0];
    var x2 = thisArray[thisArray.length-1][0];
    var theIndex = 1;
    thisArray.sort(sortArrayByIndexedItem);
    var y1 = thisArray[0][1];
    var y2 = thisArray[thisArray.length-1][1];
    theResults.push([x1, y1, x2, y2, theAdd, false]);
    var theAdd = true;
};
////////////////////////////////////
for (var o = 0; o < theResults.length; o++) {
    rectangularSelection (theResults[o][0], theResults[o][1], theResults[o][2], theResults[o][3], theResults[o][4], theResults[o][5])
};
// reset;
app.preferences.rulerUnits = originalRulerUnits;
}
};
////////////////////////////////////
////// make work path from selection //////
function saveSelectionToNewFile () {
var desc8 = new ActionDescriptor();
desc8.putClass( stringIDToTypeID( "new" ), stringIDToTypeID( "document" ) );
var idusing = stringIDToTypeID( "using" );
var ref3 = new ActionReference();
ref3.putProperty( stringIDToTypeID( "channel" ), stringIDToTypeID( "selection" ) );
desc8.putReference( idusing, ref3 );
desc8.putString( stringIDToTypeID( "channelName" ), "aaa" );
executeAction( stringIDToTypeID( "make" ), desc8, DialogModes.NO );
};
////// collect path info from actiondescriptor, indices start at 1, not 0 //////
function collectPathInfoFromDesc2023 (myDocument, thePath) {
var originalRulerUnits = app.preferences.rulerUnits;
app.preferences.rulerUnits = Units.PIXELS;
// based of functions from xbytor’s stdlib;
var idPath = charIDToTypeID( "Path" );
var ref = new ActionReference();
// check if thePath is an index or a dom-path;
if (thePath.constructor == Number) {
ref.putIndex(idPath, thePath)
}
else {
thePath.select();
var ref = new ActionReference();
ref.putEnumerated( charIDToTypeID( "Path" ), charIDToTypeID("Ordn"), charIDToTypeID("Trgt") );
};
// get stuff;
var desc = app.executeActionGet(ref);
var pname = desc.getString(cTID('PthN'));
// create new array;
var theArray = new Array;
var pathComponents = desc.getObjectValue(cTID("PthC")).getList(sTID('pathComponents'));
// for subpathitems;
for (var m = 0; m < pathComponents.count; m++) {
var listKey = pathComponents.getObjectValue(m).getList(sTID("subpathListKey"));
var operation1 = pathComponents.getObjectValue(m).getEnumerationValue(sTID("shapeOperation"));
switch (operation1) {
case 1097098272:
var operation = 1097098272 //cTID('Add ');
break;
case 1398961266:
var operation = 1398961266 //cTID('Sbtr');
break;
case 1231975538:
var operation = 1231975538 //cTID('Intr');
break;
default:
//		case 1102:
var operation = sTID('xor') //ShapeOperation.SHAPEXOR;
break;
};
// for subpathitem’s count;
for (var n = 0; n < listKey.count; n++) {
theArray.push(new Array);
var points = listKey.getObjectValue(n).getList(sTID('points'));
try {var closed = listKey.getObjectValue(n).getBoolean(sTID("closedSubpath"))}
catch (e) {var closed = false};
// for subpathitem’s segment’s number of points;
for (var o = 0; o < points.count; o++) {
var anchorObj = points.getObjectValue(o).getObjectValue(sTID("anchor"));
var anchor = [anchorObj.getUnitDoubleValue(sTID('horizontal')), anchorObj.getUnitDoubleValue(sTID('vertical'))];
var thisPoint = [anchor];
try {
var left = points.getObjectValue(o).getObjectValue(cTID("Fwd "));
var leftDirection = [left.getUnitDoubleValue(sTID('horizontal')), left.getUnitDoubleValue(sTID('vertical'))];
thisPoint.push(leftDirection)
}
catch (e) {
thisPoint.push(anchor)
};
try {
var right = points.getObjectValue(o).getObjectValue(cTID("Bwd "));
var rightDirection = [right.getUnitDoubleValue(sTID('horizontal')), right.getUnitDoubleValue(sTID('vertical'))];
thisPoint.push(rightDirection)
}
catch (e) {
thisPoint.push(anchor)
};
try {
var smoothOr = points.getObjectValue(o).getBoolean(cTID("Smoo"));
thisPoint.push(smoothOr)
}
catch (e) {thisPoint.push(false)};
theArray[theArray.length - 1].push(thisPoint);
};
theArray[theArray.length - 1].push(closed);
theArray[theArray.length - 1].push(operation);
};
};
// by xbytor, thanks to him;
function cTID (s) { return cTID[s] || cTID[s] = app.charIDToTypeID(s); };
function sTID (s) { return sTID[s] || sTID[s] = app.stringIDToTypeID(s); };
// reset;
app.preferences.rulerUnits = originalRulerUnits;
return theArray;
};
////// create a path from collectPathInfoFromDesc2023-array //////
function createPath2022(theArray, thePathsName) {
var originalRulerUnits = app.preferences.rulerUnits;
app.preferences.rulerUnits = Units.POINTS;
// thanks to xbytor;
cTID = function(s) { return app.charIDToTypeID(s); };
sTID = function(s) { return app.stringIDToTypeID(s); };

var desc1 = new ActionDescriptor();
var ref1 = new ActionReference();
ref1.putProperty(cTID('Path'), cTID('WrPt'));
desc1.putReference(sTID('null'), ref1);
var list1 = new ActionList();

for (var m = 0; m < theArray.length; m++) {
var thisSubPath = theArray[m];

var desc2 = new ActionDescriptor();
desc2.putEnumerated(sTID('shapeOperation'), sTID('shapeOperation'), thisSubPath[thisSubPath.length - 1]);
var list2 = new ActionList();
var desc3 = new ActionDescriptor();
desc3.putBoolean(cTID('Clsp'), thisSubPath[thisSubPath.length - 2]);
var list3 = new ActionList();

for (var n = 0; n < thisSubPath.length - 2; n++) {
var thisPoint = thisSubPath[n];

var desc4 = new ActionDescriptor();
var desc5 = new ActionDescriptor();
desc5.putUnitDouble(cTID('Hrzn'), cTID('#Rlt'), thisPoint[0][0]);
desc5.putUnitDouble(cTID('Vrtc'), cTID('#Rlt'), thisPoint[0][1]);
desc4.putObject(cTID('Anch'), cTID('Pnt '), desc5);
var desc6 = new ActionDescriptor();
desc6.putUnitDouble(cTID('Hrzn'), cTID('#Rlt'), thisPoint[1][0]);
desc6.putUnitDouble(cTID('Vrtc'), cTID('#Rlt'), thisPoint[1][1]);
desc4.putObject(cTID('Fwd '), cTID('Pnt '), desc6);
var desc7 = new ActionDescriptor();
desc7.putUnitDouble(cTID('Hrzn'), cTID('#Rlt'), thisPoint[2][0]);
desc7.putUnitDouble(cTID('Vrtc'), cTID('#Rlt'), thisPoint[2][1]);
desc4.putObject(cTID('Bwd '), cTID('Pnt '), desc7);
desc4.putBoolean(cTID('Smoo'), thisPoint[3]);
list3.putObject(cTID('Pthp'), desc4);

};

desc3.putList(cTID('Pts '), list3);
list2.putObject(cTID('Sbpl'), desc3);
desc2.putList(cTID('SbpL'), list2);
list1.putObject(cTID('PaCm'), desc2);
};

desc1.putList(cTID('T   '), list1);
executeAction(cTID('setd'), desc1, DialogModes.NO);

// name work path;
var desc30 = new ActionDescriptor();
var ref6 = new ActionReference();
var idPath = charIDToTypeID( "Path" );
ref6.putClass( idPath );
desc30.putReference( charIDToTypeID( "null" ), ref6 );
var ref7 = new ActionReference();
ref7.putProperty( idPath, charIDToTypeID( "WrPt" ) );
desc30.putReference( charIDToTypeID( "From" ), ref7 );
desc30.putString( charIDToTypeID( "Nm  " ), thePathsName );
executeAction( charIDToTypeID( "Mk  " ), desc30, DialogModes.NO );
/// get index;
var ref = new ActionReference();
ref.putProperty(stringIDToTypeID("property"), stringIDToTypeID("itemIndex"));
ref.putEnumerated( charIDToTypeID("Path"), charIDToTypeID("Ordn"), charIDToTypeID("Trgt") );
var pathDesc = executeActionGet(ref);
app.preferences.rulerUnits = originalRulerUnits;
// return index;
return pathDesc.getInteger(stringIDToTypeID("itemIndex"))
};
////// make work path from selection //////
function makeWorkPath (theTolerance) {
// =======================================================
var idMk = charIDToTypeID( "Mk  " );
var desc5 = new ActionDescriptor();
var idnull = charIDToTypeID( "null" );
var ref3 = new ActionReference();
var idPath = charIDToTypeID( "Path" );
ref3.putClass( idPath );
desc5.putReference( idnull, ref3 );
var idFrom = charIDToTypeID( "From" );
var ref4 = new ActionReference();
var idcsel = charIDToTypeID( "csel" );
var idfsel = charIDToTypeID( "fsel" );
ref4.putProperty( idcsel, idfsel );
desc5.putReference( idFrom, ref4 );
var idTlrn = charIDToTypeID( "Tlrn" );
var idPxl = charIDToTypeID( "#Pxl" );
desc5.putUnitDouble( idTlrn, idPxl, theTolerance );
executeAction( idMk, desc5, DialogModes.NO );
/// get index;
var ref = new ActionReference();
ref.putProperty(stringIDToTypeID("property"), stringIDToTypeID("itemIndex"));
ref.putEnumerated( charIDToTypeID("Path"), charIDToTypeID("Ordn"), charIDToTypeID("Trgt") );
var pathDesc = executeActionGet(ref);
// return index;
return pathDesc.getInteger(stringIDToTypeID("itemIndex"))
};
////// make a rectangular selection //////
function rectangularSelection (x1, y1, x2, y2, theAdd, theIntersect) {
if (theAdd == false || theAdd == undefined) {var idset = stringIDToTypeID( "set" )}
else {var idset = stringIDToTypeID( "addTo" )};
if (theIntersect == true) {var idset = stringIDToTypeID( "interfaceWhite" );};
var idpixelsUnit = stringIDToTypeID( "pixelsUnit" );
var desc16 = new ActionDescriptor();
var ref2 = new ActionReference();
ref2.putProperty( stringIDToTypeID( "channel" ), stringIDToTypeID( "selection" ) );
desc16.putReference( stringIDToTypeID( "null" ), ref2 );
var desc17 = new ActionDescriptor();
desc17.putUnitDouble( stringIDToTypeID( "top" ), idpixelsUnit, y1 );
desc17.putUnitDouble( stringIDToTypeID( "left" ), idpixelsUnit, x1 );
desc17.putUnitDouble( stringIDToTypeID( "bottom" ), idpixelsUnit, y2 );
desc17.putUnitDouble( stringIDToTypeID( "right" ), idpixelsUnit, x2 );
desc16.putObject( stringIDToTypeID( "to" ), stringIDToTypeID( "rectangle" ), desc17 );
if(theAdd == true) desc16.putEnumerated( stringIDToTypeID( "selectionModifier" ), stringIDToTypeID( "selectionModifierType" ), stringIDToTypeID( "addToSelection" ) );
executeAction( idset, desc16, DialogModes.NO );
};
////// sort a double array, thanks to sam, http://www.rhinocerus.net/forum/lang-javascript/ //////
function sortArrayByIndexedItem(a,b) {
//var theIndex = 1;
if (a[theIndex]<b[theIndex]) return -1;
if (a[theIndex]>b[theIndex]) return 1;
return 0;
};
////// check for selection //////
function hasSelection(){
var ref10 = new ActionReference();
ref10.putProperty(stringIDToTypeID("property"), stringIDToTypeID("selection"));
ref10.putEnumerated( charIDToTypeID( "Dcmn" ), charIDToTypeID( "Ordn" ), charIDToTypeID( "Trgt" ) );
var docDesc = executeActionGet(ref10);
return docDesc.hasKey(stringIDToTypeID("selection"));
};

4 replies

Legend
March 27, 2024

The manual way is turn on snapping, drag guides to each selection, and manually add a rectangular selection. Honestly I'd probably just do that and I'm a big user of scripts.

Stephen Marsh
Community Expert
Community Expert
March 28, 2024
quote

The manual way is turn on snapping, drag guides to each selection, and manually add a rectangular selection. Honestly I'd probably just do that and I'm a big user of scripts.


By @Lumigraphics

 

For how many selections per document? For how many documents? For how many times a day, week or year?

 

It would all come down to what a PITA this was, I'm guessing that this is the case for the OP.

 

 

c.pfaffenbichler
Community Expert
c.pfaffenbichlerCommunity ExpertCorrect answer
Community Expert
March 27, 2024

// create rectangular sub selections for irregular ones;
// 2024, use it at your own risk;
if (app.documents.length > 0) {
if (hasSelection() == true) {
// set to pixels;
var originalRulerUnits = app.preferences.rulerUnits;
app.preferences.rulerUnits = Units.PIXELS;
////////////////////////////////////
saveSelectionToNewFile ();
var myDocument = app.activeDocument;
var myLayer = myDocument.activeLayer;
myLayer.threshold(1);
myDocument.resizeImage(new UnitValue (200, "%"), new UnitValue (200, "%"), undefined, ResampleMethod.NEARESTNEIGHBOR);
myDocument.selection.load(myDocument.channels[0], SelectionType.REPLACE);
var thePath = makeWorkPath(0);
myDocument.resizeImage(new UnitValue (50, "%"), new UnitValue (50, "%"), undefined, ResampleMethod.NEARESTNEIGHBOR);
var thePathArray = collectPathInfoFromDesc2023 (myDocument, thePath);
myDocument.close(SaveOptions.DONOTSAVECHANGES);
////////////////////////////////////
var theResults = new Array;
var theAdd = false;
for (var m = 0; m < thePathArray.length; m++) {
    var thisOne = thePathArray[m];
    var thisArray = new Array;
    for (var n = 0; n < thisOne.length-2; n++) {
        thisArray.push(thisOne[n][0])
    };
    var theIndex = 0;
    thisArray.sort(sortArrayByIndexedItem);
    var x1 = thisArray[0][0];
    var x2 = thisArray[thisArray.length-1][0];
    var theIndex = 1;
    thisArray.sort(sortArrayByIndexedItem);
    var y1 = thisArray[0][1];
    var y2 = thisArray[thisArray.length-1][1];
    theResults.push([x1, y1, x2, y2, theAdd, false]);
    var theAdd = true;
};
////////////////////////////////////
for (var o = 0; o < theResults.length; o++) {
    rectangularSelection (theResults[o][0], theResults[o][1], theResults[o][2], theResults[o][3], theResults[o][4], theResults[o][5])
};
// reset;
app.preferences.rulerUnits = originalRulerUnits;
}
};
////////////////////////////////////
////// make work path from selection //////
function saveSelectionToNewFile () {
var desc8 = new ActionDescriptor();
desc8.putClass( stringIDToTypeID( "new" ), stringIDToTypeID( "document" ) );
var idusing = stringIDToTypeID( "using" );
var ref3 = new ActionReference();
ref3.putProperty( stringIDToTypeID( "channel" ), stringIDToTypeID( "selection" ) );
desc8.putReference( idusing, ref3 );
desc8.putString( stringIDToTypeID( "channelName" ), "aaa" );
executeAction( stringIDToTypeID( "make" ), desc8, DialogModes.NO );
};
////// collect path info from actiondescriptor, indices start at 1, not 0 //////
function collectPathInfoFromDesc2023 (myDocument, thePath) {
var originalRulerUnits = app.preferences.rulerUnits;
app.preferences.rulerUnits = Units.PIXELS;
// based of functions from xbytor’s stdlib;
var idPath = charIDToTypeID( "Path" );
var ref = new ActionReference();
// check if thePath is an index or a dom-path;
if (thePath.constructor == Number) {
ref.putIndex(idPath, thePath)
}
else {
thePath.select();
var ref = new ActionReference();
ref.putEnumerated( charIDToTypeID( "Path" ), charIDToTypeID("Ordn"), charIDToTypeID("Trgt") );
};
// get stuff;
var desc = app.executeActionGet(ref);
var pname = desc.getString(cTID('PthN'));
// create new array;
var theArray = new Array;
var pathComponents = desc.getObjectValue(cTID("PthC")).getList(sTID('pathComponents'));
// for subpathitems;
for (var m = 0; m < pathComponents.count; m++) {
var listKey = pathComponents.getObjectValue(m).getList(sTID("subpathListKey"));
var operation1 = pathComponents.getObjectValue(m).getEnumerationValue(sTID("shapeOperation"));
switch (operation1) {
case 1097098272:
var operation = 1097098272 //cTID('Add ');
break;
case 1398961266:
var operation = 1398961266 //cTID('Sbtr');
break;
case 1231975538:
var operation = 1231975538 //cTID('Intr');
break;
default:
//		case 1102:
var operation = sTID('xor') //ShapeOperation.SHAPEXOR;
break;
};
// for subpathitem’s count;
for (var n = 0; n < listKey.count; n++) {
theArray.push(new Array);
var points = listKey.getObjectValue(n).getList(sTID('points'));
try {var closed = listKey.getObjectValue(n).getBoolean(sTID("closedSubpath"))}
catch (e) {var closed = false};
// for subpathitem’s segment’s number of points;
for (var o = 0; o < points.count; o++) {
var anchorObj = points.getObjectValue(o).getObjectValue(sTID("anchor"));
var anchor = [anchorObj.getUnitDoubleValue(sTID('horizontal')), anchorObj.getUnitDoubleValue(sTID('vertical'))];
var thisPoint = [anchor];
try {
var left = points.getObjectValue(o).getObjectValue(cTID("Fwd "));
var leftDirection = [left.getUnitDoubleValue(sTID('horizontal')), left.getUnitDoubleValue(sTID('vertical'))];
thisPoint.push(leftDirection)
}
catch (e) {
thisPoint.push(anchor)
};
try {
var right = points.getObjectValue(o).getObjectValue(cTID("Bwd "));
var rightDirection = [right.getUnitDoubleValue(sTID('horizontal')), right.getUnitDoubleValue(sTID('vertical'))];
thisPoint.push(rightDirection)
}
catch (e) {
thisPoint.push(anchor)
};
try {
var smoothOr = points.getObjectValue(o).getBoolean(cTID("Smoo"));
thisPoint.push(smoothOr)
}
catch (e) {thisPoint.push(false)};
theArray[theArray.length - 1].push(thisPoint);
};
theArray[theArray.length - 1].push(closed);
theArray[theArray.length - 1].push(operation);
};
};
// by xbytor, thanks to him;
function cTID (s) { return cTID[s] || cTID[s] = app.charIDToTypeID(s); };
function sTID (s) { return sTID[s] || sTID[s] = app.stringIDToTypeID(s); };
// reset;
app.preferences.rulerUnits = originalRulerUnits;
return theArray;
};
////// create a path from collectPathInfoFromDesc2023-array //////
function createPath2022(theArray, thePathsName) {
var originalRulerUnits = app.preferences.rulerUnits;
app.preferences.rulerUnits = Units.POINTS;
// thanks to xbytor;
cTID = function(s) { return app.charIDToTypeID(s); };
sTID = function(s) { return app.stringIDToTypeID(s); };

var desc1 = new ActionDescriptor();
var ref1 = new ActionReference();
ref1.putProperty(cTID('Path'), cTID('WrPt'));
desc1.putReference(sTID('null'), ref1);
var list1 = new ActionList();

for (var m = 0; m < theArray.length; m++) {
var thisSubPath = theArray[m];

var desc2 = new ActionDescriptor();
desc2.putEnumerated(sTID('shapeOperation'), sTID('shapeOperation'), thisSubPath[thisSubPath.length - 1]);
var list2 = new ActionList();
var desc3 = new ActionDescriptor();
desc3.putBoolean(cTID('Clsp'), thisSubPath[thisSubPath.length - 2]);
var list3 = new ActionList();

for (var n = 0; n < thisSubPath.length - 2; n++) {
var thisPoint = thisSubPath[n];

var desc4 = new ActionDescriptor();
var desc5 = new ActionDescriptor();
desc5.putUnitDouble(cTID('Hrzn'), cTID('#Rlt'), thisPoint[0][0]);
desc5.putUnitDouble(cTID('Vrtc'), cTID('#Rlt'), thisPoint[0][1]);
desc4.putObject(cTID('Anch'), cTID('Pnt '), desc5);
var desc6 = new ActionDescriptor();
desc6.putUnitDouble(cTID('Hrzn'), cTID('#Rlt'), thisPoint[1][0]);
desc6.putUnitDouble(cTID('Vrtc'), cTID('#Rlt'), thisPoint[1][1]);
desc4.putObject(cTID('Fwd '), cTID('Pnt '), desc6);
var desc7 = new ActionDescriptor();
desc7.putUnitDouble(cTID('Hrzn'), cTID('#Rlt'), thisPoint[2][0]);
desc7.putUnitDouble(cTID('Vrtc'), cTID('#Rlt'), thisPoint[2][1]);
desc4.putObject(cTID('Bwd '), cTID('Pnt '), desc7);
desc4.putBoolean(cTID('Smoo'), thisPoint[3]);
list3.putObject(cTID('Pthp'), desc4);

};

desc3.putList(cTID('Pts '), list3);
list2.putObject(cTID('Sbpl'), desc3);
desc2.putList(cTID('SbpL'), list2);
list1.putObject(cTID('PaCm'), desc2);
};

desc1.putList(cTID('T   '), list1);
executeAction(cTID('setd'), desc1, DialogModes.NO);

// name work path;
var desc30 = new ActionDescriptor();
var ref6 = new ActionReference();
var idPath = charIDToTypeID( "Path" );
ref6.putClass( idPath );
desc30.putReference( charIDToTypeID( "null" ), ref6 );
var ref7 = new ActionReference();
ref7.putProperty( idPath, charIDToTypeID( "WrPt" ) );
desc30.putReference( charIDToTypeID( "From" ), ref7 );
desc30.putString( charIDToTypeID( "Nm  " ), thePathsName );
executeAction( charIDToTypeID( "Mk  " ), desc30, DialogModes.NO );
/// get index;
var ref = new ActionReference();
ref.putProperty(stringIDToTypeID("property"), stringIDToTypeID("itemIndex"));
ref.putEnumerated( charIDToTypeID("Path"), charIDToTypeID("Ordn"), charIDToTypeID("Trgt") );
var pathDesc = executeActionGet(ref);
app.preferences.rulerUnits = originalRulerUnits;
// return index;
return pathDesc.getInteger(stringIDToTypeID("itemIndex"))
};
////// make work path from selection //////
function makeWorkPath (theTolerance) {
// =======================================================
var idMk = charIDToTypeID( "Mk  " );
var desc5 = new ActionDescriptor();
var idnull = charIDToTypeID( "null" );
var ref3 = new ActionReference();
var idPath = charIDToTypeID( "Path" );
ref3.putClass( idPath );
desc5.putReference( idnull, ref3 );
var idFrom = charIDToTypeID( "From" );
var ref4 = new ActionReference();
var idcsel = charIDToTypeID( "csel" );
var idfsel = charIDToTypeID( "fsel" );
ref4.putProperty( idcsel, idfsel );
desc5.putReference( idFrom, ref4 );
var idTlrn = charIDToTypeID( "Tlrn" );
var idPxl = charIDToTypeID( "#Pxl" );
desc5.putUnitDouble( idTlrn, idPxl, theTolerance );
executeAction( idMk, desc5, DialogModes.NO );
/// get index;
var ref = new ActionReference();
ref.putProperty(stringIDToTypeID("property"), stringIDToTypeID("itemIndex"));
ref.putEnumerated( charIDToTypeID("Path"), charIDToTypeID("Ordn"), charIDToTypeID("Trgt") );
var pathDesc = executeActionGet(ref);
// return index;
return pathDesc.getInteger(stringIDToTypeID("itemIndex"))
};
////// make a rectangular selection //////
function rectangularSelection (x1, y1, x2, y2, theAdd, theIntersect) {
if (theAdd == false || theAdd == undefined) {var idset = stringIDToTypeID( "set" )}
else {var idset = stringIDToTypeID( "addTo" )};
if (theIntersect == true) {var idset = stringIDToTypeID( "interfaceWhite" );};
var idpixelsUnit = stringIDToTypeID( "pixelsUnit" );
var desc16 = new ActionDescriptor();
var ref2 = new ActionReference();
ref2.putProperty( stringIDToTypeID( "channel" ), stringIDToTypeID( "selection" ) );
desc16.putReference( stringIDToTypeID( "null" ), ref2 );
var desc17 = new ActionDescriptor();
desc17.putUnitDouble( stringIDToTypeID( "top" ), idpixelsUnit, y1 );
desc17.putUnitDouble( stringIDToTypeID( "left" ), idpixelsUnit, x1 );
desc17.putUnitDouble( stringIDToTypeID( "bottom" ), idpixelsUnit, y2 );
desc17.putUnitDouble( stringIDToTypeID( "right" ), idpixelsUnit, x2 );
desc16.putObject( stringIDToTypeID( "to" ), stringIDToTypeID( "rectangle" ), desc17 );
if(theAdd == true) desc16.putEnumerated( stringIDToTypeID( "selectionModifier" ), stringIDToTypeID( "selectionModifierType" ), stringIDToTypeID( "addToSelection" ) );
executeAction( idset, desc16, DialogModes.NO );
};
////// sort a double array, thanks to sam, http://www.rhinocerus.net/forum/lang-javascript/ //////
function sortArrayByIndexedItem(a,b) {
//var theIndex = 1;
if (a[theIndex]<b[theIndex]) return -1;
if (a[theIndex]>b[theIndex]) return 1;
return 0;
};
////// check for selection //////
function hasSelection(){
var ref10 = new ActionReference();
ref10.putProperty(stringIDToTypeID("property"), stringIDToTypeID("selection"));
ref10.putEnumerated( charIDToTypeID( "Dcmn" ), charIDToTypeID( "Ordn" ), charIDToTypeID( "Trgt" ) );
var docDesc = executeActionGet(ref10);
return docDesc.hasKey(stringIDToTypeID("selection"));
};
Stephen Marsh
Community Expert
Community Expert
March 28, 2024

@w30290083o9nn 

 

If this script from @c.pfaffenbichler works for you,  please don't forget to mark that reply as a correct answer.

Stephen Marsh
Community Expert
Community Expert
March 27, 2024

One method, you can use the following script from @c.pfaffenbichler 

 

/* https://community.adobe.com/t5/photoshop-ecosystem-discussions/how-can-i-automatically-create-a-rectangular-layer-mask-from-an-irregularly-shaped-selection/m-p/4905764 */
// make selection rectangular
// 2013, use it at your own risk;

#target photoshop

if (app.documents.length > 0) {
    var myDocument = app.activeDocument;
    try {
        var theBounds = myDocument.selection.bounds;
        var theArray = [[theBounds[0], theBounds[1]], [theBounds[2], theBounds[1]], [theBounds[2], theBounds[3]], [theBounds[0], theBounds[3]]];
        myDocument.selection.select(theArray, SelectionType.REPLACE, 0, false);
    }
    catch (e) { }
}

 

https://prepression.blogspot.com/2017/11/downloading-and-installing-adobe-scripts.html

Stephen Marsh
Community Expert
Community Expert
March 27, 2024

I just saw your new post that came in while I was writing mine...

 

You could use Layer > New > Layer via copy (CTRL/CMD J)

 

Then run the following script:

 

https://photoshopscripts.wordpress.com/2012/12/09/split-to-layers/

 

So that you have individual layers from each separate selection.

 

Then another script can loop over the layers and convert each transparency channel selection to a rectangular selection.

 

You can combine each of these manual steps into an action or a single script.

Known Participant
March 27, 2024

I have a piece of code that can turn an irregular selection into a rectangular selection, but it cannot handle multiple irregular selections. For example, if there are N irregular selections, it cannot achieve the transformation for all of them.

// Set the ruler units to pixels
preferences.rulerUnits = Units.PIXELS;

// Get the coordinates and dimensions of the current selection
var rect = app.activeDocument.selection.bounds;
var x = rect[0].value;
var y = rect[1].value;
var width = rect[2].value - x;
var height = rect[3].value - y;

// Extract coordinate and dimension information
var xCoord = x.toString().replace(' px', '');
var yCoord = y.toString().replace(' px', '');
var rectWidth = width.toString().replace(' px', '');
var rectHeight = height.toString().replace(' px', '');

// Calculate the position of the new selection
var newX = xCoord;
var newY = yCoord;
var newWidth = Number(rectWidth) + Number(xCoord);
var newHeight = Number(rectHeight) + Number(yCoord);

// Create an ActionDescriptor for the new selection
var actionDescriptor = new ActionDescriptor();
var actionReference = new ActionReference();
actionReference.putProperty(stringIDToTypeID("channel"), stringIDToTypeID("selection"));
actionDescriptor.putReference(stringIDToTypeID("null"), actionReference);

var newSelectionDescriptor = new ActionDescriptor();
newSelectionDescriptor.putUnitDouble(stringIDToTypeID("top"), stringIDToTypeID("pixelsUnit"), newY);
newSelectionDescriptor.putUnitDouble(stringIDToTypeID("left"), stringIDToTypeID("pixelsUnit"), newX);
newSelectionDescriptor.putUnitDouble(stringIDToTypeID("bottom"), stringIDToTypeID("pixelsUnit"), newHeight);
newSelectionDescriptor.putUnitDouble(stringIDToTypeID("right"), stringIDToTypeID("pixelsUnit"), newWidth);

actionDescriptor.putObject(stringIDToTypeID("to"), stringIDToTypeID("rectangle"), newSelectionDescriptor);

// Add the new selection
executeAction(stringIDToTypeID("addTo"), actionDescriptor, DialogModes.NO);

// Drawing the rectangular selection is complete