@Calvin21914323wi10 – Try this:
/*
Auto Crop to Nearest Aspect Ratio.jsx
https://community.adobe.com/t5/photoshop-ecosystem-discussions/how-to-using-script-crop-image-by-aspect-ratio/td-p/13938028
From:
https://community.adobe.com/t5/photoshop-ecosystem-discussions/is-possible-to-write-a-script-that-can-auto-crop-image-to-best-fit-aspect-ratio/td-p/13883327
By Calvin21914323wi10
Based on code from c.pfaffenbichler
#2 - Amendments by Stephen Marsh
*/
#target photoshop
if (app.documents.length > 0) {
app.togglePalettes();
var originalRulerUnits = app.preferences.rulerUnits;
app.preferences.rulerUnits = Units.PIXELS;
var myDocument = activeDocument;
var theW = myDocument.width.value;
var theH = myDocument.height.value;
var theProportion = theW / theH;
var theProportions = [[1,3],[1,2],[2,3], [5,7], [3,4], [4,5], [1,1], [5,4], [4,3], [7,5], [3,2], [2,1], [3,1]];
var theResult = theProportions.sort(sortArrayByDifference)[0];
var thisProp = theResult[0] / theResult[1];
if (theProportion < thisProp) {
var targetW = theW;
var targetH = theW * theResult[1] / theResult[0];
} else {
var targetW = theH * theResult[0] / theResult[1];
var targetH = theH;
}
// Calculate centre crop
var diffW = theW - targetW;
var offsetW = diffW / 2;
var diffH = theH - targetH;
var offsetH = diffH / 2;
var bounds = [offsetW, offsetH, Math.round(targetW) + offsetW, Math.round(targetH) + offsetH];
//var bounds = [0, 0, targetW, targetH];
// Disable or remove the alert for batch processing
alert("At the aspect ratio " + theResult.join(":") + " the image would be" + "\n" + targetW + " x " + targetH + " px");
/* https://theiviaxx.github.io/photoshop-docs/Photoshop/Document/crop.html */
// Crop to bounds
app.activeDocument.crop(bounds,null,null,null);
app.preferences.rulerUnits = originalRulerUnits;
app.togglePalettes();
}
////// sort by difference to a number //////
function sortArrayByDifference(a, b) {
if (Math.abs((a[0] / a[1]) - theProportion) < Math.abs((b[0] / b[1]) - theProportion)) return -1;
if (Math.abs((a[0] / a[1]) - theProportion) > Math.abs((b[0] / b[1]) - theProportion)) return 1;
return 0;
}
P.S. I have revised the original code a little, make sure that you are using the updated version #2.