/* 
Author: Derek Nelsen 2017

Description: PSD script for automating image batching for large, 
normal, and thumbnail sized images

Instructions: Run this script in photoshop. Open the folder with your images.
Open the folder for image output.

Change the image size adjustment by changing the large, normal, and thumbnail variables.
*/


// variables
var inputFolder = Folder.selectDialog("SELECT A FOLDER OF IMAGES TO RESIZE");
var outputFolder = inputFolder

// check that the folder has files in it
if (inputFolder != null) {
    var fileList = inputFolder.getFiles(/.+\.(?:gif|jpe?g|[ew]mf|eps|tiff?|psd|pdf|bmp|png)$/i);
} else {
    alert("Couldn't find any files. Check your directory path and try again.");
    Exit();
}

// set background color
var BGcolor = new SolidColor();  
BGcolor.rgb.red = 255;  
BGcolor.rgb.green = 255;  
BGcolor.rgb.blue = 255;  
    
// set your color as background color  
backgroundColor.rgb.hexValue = BGcolor.rgb.hexValue;  

//  new image sizes
var large = 900;
var normal = 600;
var thumbnail = 300;

//  new image name extentions
var largeNameExt = '_l';
var normalNameExt = '_n';
var thumbnailNameExt = '_t';

// set jpeg save options
var jpegSaveOptions = new JPEGSaveOptions();
jpegSaveOptions.embedColorProfile = true;
jpegSaveOptions.formatOptions = FormatOptions.STANDARDBASELINE;
jpegSaveOptions.matte = MatteType.NONE;
jpegSaveOptions.quality = 12;

// error logging
var errors = [];

/* 
Function: createFolder
Description: creates the new folders for export 
imageSize: the new image size used to create the folder path
*/
function createFolders(imageSize) {
    var addFolder = new Folder(outputFolder + '/' + imageSize.toString() + 'px' + '/');
    addFolder.create();
} // createFolders


/* 
Function: createImages
Description: scales the image then exports the jpeg
imageSize: the new image size to be exported
*/
function createImages() {

    // add new folder paths
    createFolders(large);
    createFolders(normal);
    createFolders(thumbnail);

    // trim the images then resize
    for(var i = 0; i < fileList.length; i++) {

        // open the image
        try {
            var doc = app.open(fileList[i]);
            // set the output locations and names

            // check only filenames of these types
            var fileName = fileList[i].name.replace(/\.(?:gif|jpe?g|[ew]mf|eps|tiff?|psd|pdf|bmp|png)$/, '');
            var saveImgLarge = new File(outputFolder + "/" + large.toString() + 'px' + '/' + fileName + largeNameExt);
            var saveImgNormal = new File(outputFolder + "/" + normal.toString() + 'px' + '/' + fileName + normalNameExt);
            var saveImgThumbnail = new File(outputFolder + "/" + thumbnail.toString() + 'px' + '/' + fileName + thumbnailNameExt);
            
            // trim whitespace
            doc.trim();

            // if height > width (portrait-mode) resize based on height otherwise, resize based on width
            if (doc.height > doc.width) {
                doc.resizeImage(null, UnitValue(large, "px"), 72, ResampleMethod.BICUBICAUTOMATIC);
            }
            else {
                doc.resizeImage(UnitValue(large, "px"), null, 72, ResampleMethod.BICUBICAUTOMATIC);
            }

            // even out the dimentions to a square Large x Large
            doc.resizeCanvas(large, large, AnchorPosition.MIDDLECENTER);
            doc.saveAs(saveImgLarge, jpegSaveOptions, true, Extension.LOWERCASE);

            // Normal x Normal
            doc.resizeImage(UnitValue(normal, "px"), UnitValue(normal, "px"), 72, ResampleMethod.BICUBICAUTOMATIC);
            doc.saveAs(saveImgNormal, jpegSaveOptions, true, Extension.LOWERCASE);

            // Small x Small
            doc.resizeImage(UnitValue(thumbnail, "px"), UnitValue(thumbnail, "px"), 72, ResampleMethod.BICUBICAUTOMATIC);
            doc.saveAs(saveImgThumbnail, jpegSaveOptions, true, Extension.LOWERCASE);

            doc.close(SaveOptions.DONOTSAVECHANGES);
        } catch (err) {

            // log errors for reference
            errors.push(fileList[i].name);

        }
    } // end for
}

createImages();

if (errors.length > 0) {
    alert("Oops! We ran into some errors.\nWhile the program did run successfully, you will still need to double-check the files listed below for issues like these:" + "\n\n1) Files are corrupt (files don't open, or cause an error when you try to open them)\n2) Files have unusual characters in their file names\n3) Files are not one of these types of image files:\ngif, jpeg, jpg, eps, tiff, tif, psd, pdf, bmp, png" + "\n\n*** FILE ERRORS ***\n" + errors.join("\n"));
} else {
    alert("Task Completed!");
}
