Try this revised code:
[CODE=javascript]// Open folder selection dialog
var inputFolder = Folder.selectDialog("Select a folder with images");
// Check if a valid folder was selected
if (inputFolder) {
var files = inputFolder.getFiles(/\.(jpg|jpeg|png|tif|tiff|psd)$/i);
for (var i = 0; i < files.length; i++) {
var file = files[i];
if (file instanceof File) {
try {
open(file);
// Get the active document
var doc = app.activeDocument;
// Get original width and height
var originalWidth = doc.width;
var originalHeight = doc.height;
// Determine the new canvas size (largest dimension)
var newSize = Math.max(originalWidth, originalHeight);
// Resize canvas to make it square (1:1 ratio)
doc.resizeCanvas(newSize, newSize, AnchorPosition.MIDDLECENTER);
// Deselect any active selection
doc.selection.deselect();
// Store reference to the original image layer
var imageLayer = doc.activeLayer;
imageLayer.name = "Original Image"; // Name it for clarity
// Create a new solid white background layer
var whiteBackground = doc.artLayers.add();
whiteBackground.name = "White Background";
// Fill the new layer with white
doc.activeLayer = whiteBackground;
var white = new SolidColor();
white.rgb.red = 255;
white.rgb.green = 255;
white.rgb.blue = 255;
doc.selection.selectAll();
doc.selection.fill(white);
doc.selection.deselect();
// Move the white background layer to the bottom
var bottomLayer = doc.artLayers[doc.artLayers.length - 1];
whiteBackground.move(bottomLayer, ElementPlacement.PLACEAFTER);
// Move the original image layer to the top
var topLayer = doc.artLayers[0];
imageLayer.move(topLayer, ElementPlacement.PLACEBEFORE);
// Flatten the image to merge layers correctly
doc.flatten();
// Save the modified image
var saveFile = new File(file.path + "/" + file.name);
var saveOptions = new JPEGSaveOptions();
saveOptions.quality = 12; // Max quality
doc.saveAs(saveFile, saveOptions, true, Extension.LOWERCASE);
// Close the document without saving additional changes
doc.close(SaveOptions.DONOTSAVECHANGES);
} catch (e) {
alert("Error processing file: " + file.name + "\n" + e.message);
}
}
}
alert("Batch processing completed!");
} else {
alert("No folder selected. Process canceled.");
}[/CODE]