Crop image in script like with crop tool
How to crop image using javascript the same way like photoshop do this with crop tool?
I have a folder with images and i want to crop every image like photoshop doing with these constant sizes in inches:
var neededSizes = [
[5,7],
[8, 10],
[9, 12],
[11, 14],
[16, 20],
[18, 24],
[24, 36],
[23 + 3/8, 33 + 1/8]
]So for every photo i need to get 8 more cropped photos which saving in folder with same name as image filename.
I wrote part of code and now i can create and save these photos in folders, but i totally don't understand how to crop image the same way as crop tool... So here is a code:
// Took first code variation from Nathaniel Young (nyoungstudios)
function main() {
// parameters
var quality = 12;
var neededSizes = [
[5,7],
[8, 10],
[9, 12],
[11, 14],
[16, 20],
[18, 24],
[24, 36],
[23 + 3/8, 33 + 1/8]
]
// opens folder dialog for user to select the folder to process
var inputFolder = Folder.selectDialog("Choose a source folder");
// checks if user selected no folder
if (inputFolder == null) {
return;
}
// regular expression to match file types
var fileTypes = new RegExp('.*.jpg|.*.png|.*.tif|.*.jpeg', 'i');
// gets list of files that match regular expression
var fileList = inputFolder.getFiles(fileTypes);
// loops over each file in the folder
for (var i = 0; i < fileList.length; i++) {
// gets file path name
var filePathName = fileList[i].toString();
// removes the file extension
var baseDocName = filePathName.substring(filePathName.lastIndexOf('/') + 1, filePathName.lastIndexOf('.'));
var saveLocation = filePathName.substring(0, filePathName.lastIndexOf('/') + 1) + baseDocName + '/';
// Creates folder if it does not already exist
var folder = new Folder(saveLocation);
if (!folder.exists) {
folder.create();
}
//block to identify vertical or horizontal images
// loop over each crop format
for (var iSize = 0; iSize < neededSizes.length; iSize++) {
// appends the width of the document
newDocName = baseDocName + '_' + neededSizes[iSize][0] + 'x' + neededSizes[iSize][1];
displayDialogs = DialogModes.NO
// opens photo
var imgFile = app.open(new File(filePathName));
// gets the current active document open
currentDocument = app.activeDocument;
// crop photo
app.preferences.rulerUnits = Units.INCHES
currentDocument.resizeCanvas(neededSizes[iSize][0], neededSizes[iSize][1])
// currentDocument.crop(new Array(100, 200, 400, 500), 45, 20, 20);
// saves jpg photo
var newJpgFile = new File(saveLocation + newDocName + '.jpg');
jpgSaveOptions = new JPEGSaveOptions();
jpgSaveOptions.quality = quality;
currentDocument.saveAs(newJpgFile, jpgSaveOptions, true, Extension.LOWERCASE);
// closes photoshop file
currentDocument.close(SaveOptions.DONOTSAVECHANGES);
}
}
};
main();