最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Why will Photoshop Batch files not compress - Stack Overflow

programmeradmin3浏览0评论

I am attempting to resize and compress a batch file is Photoshop. It does everything else, resize, create folders, and save. But it does not appear to be compressing the images. Any idea why this would be? I have tried many variations of this, I did use Google and LLMs. The only difference I get is complete failure. As said, this will almost work, it just will not compress the images.



// 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


// Set jpeg save options with quality adjustments
function setJPEGQuality(saveOptions, targetSizeKB) {
    var quality = 12; // Start with maximum quality
    var tempFile = new File("~/Desktop/temp.jpg");
    
    do {
        saveOptions.quality = quality;
        doc.saveAs(tempFile, saveOptions, true, Extension.LOWERCASE);
        var fileSize = tempFile.length / 1024; // Convert bytes to KB

        if (fileSize > targetSizeKB) {
            quality -= 1; // Reduce quality to decrease file size
        } else {
            break; // Exit the loop if target size is met
        }
    } while (quality > 0);

    tempFile.remove(); // Clean up the temp file
}

// CreateImages function
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
            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 + '.jpg');
            var saveImgNormal = new File(outputFolder + "/" + normal.toString() + 'px' + '/' + fileName + normalNameExt + '.jpg');
            var saveImgThumbnail = new File(outputFolder + "/" + thumbnail.toString() + 'px' + '/' + fileName + thumbnailNameExt + '.jpg');

            // trim whitespace
            doc.trim();

            // Resize and save images
            // Large
            if (doc.height > doc.width) {
                doc.resizeImage(null, UnitValue(large, "px"), 72, ResampleMethod.BICUBICAUTOMATIC);
            } else {
                doc.resizeImage(UnitValue(large, "px"), null, 72, ResampleMethod.BICUBICAUTOMATIC);
            }
            doc.resizeCanvas(large, large, AnchorPosition.MIDDLECENTER);
            setJPEGQuality(jpegSaveOptions, 70); // Adjust quality to target size 70 KB
            doc.saveAs(saveImgLarge, jpegSaveOptions, true, Extension.LOWERCASE);

            // Normal
            doc.resizeImage(UnitValue(normal, "px"), UnitValue(normal, "px"), 72, ResampleMethod.BICUBICAUTOMATIC);
            setJPEGQuality(jpegSaveOptions, 50); // Adjust quality to target size 50 KB
            doc.saveAs(saveImgNormal, jpegSaveOptions, true, Extension.LOWERCASE);

            // Thumbnail
            doc.resizeImage(UnitValue(thumbnail, "px"), UnitValue(thumbnail, "px"), 72, ResampleMethod.BICUBICAUTOMATIC);
            setJPEGQuality(jpegSaveOptions, 20); // Adjust quality to target size 20 KB
            doc.saveAs(saveImgThumbnail, jpegSaveOptions, true, Extension.LOWERCASE);

            doc.close(SaveOptions.DONOTSAVECHANGES);
        } catch (err) {
            errors.push(fileList[i].name);
        }
    }
}


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!");
}

I tried the above code (any many variations). I am expecting it to resize and compress images.

I am attempting to resize and compress a batch file is Photoshop. It does everything else, resize, create folders, and save. But it does not appear to be compressing the images. Any idea why this would be? I have tried many variations of this, I did use Google and LLMs. The only difference I get is complete failure. As said, this will almost work, it just will not compress the images.



// 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


// Set jpeg save options with quality adjustments
function setJPEGQuality(saveOptions, targetSizeKB) {
    var quality = 12; // Start with maximum quality
    var tempFile = new File("~/Desktop/temp.jpg");
    
    do {
        saveOptions.quality = quality;
        doc.saveAs(tempFile, saveOptions, true, Extension.LOWERCASE);
        var fileSize = tempFile.length / 1024; // Convert bytes to KB

        if (fileSize > targetSizeKB) {
            quality -= 1; // Reduce quality to decrease file size
        } else {
            break; // Exit the loop if target size is met
        }
    } while (quality > 0);

    tempFile.remove(); // Clean up the temp file
}

// CreateImages function
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
            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 + '.jpg');
            var saveImgNormal = new File(outputFolder + "/" + normal.toString() + 'px' + '/' + fileName + normalNameExt + '.jpg');
            var saveImgThumbnail = new File(outputFolder + "/" + thumbnail.toString() + 'px' + '/' + fileName + thumbnailNameExt + '.jpg');

            // trim whitespace
            doc.trim();

            // Resize and save images
            // Large
            if (doc.height > doc.width) {
                doc.resizeImage(null, UnitValue(large, "px"), 72, ResampleMethod.BICUBICAUTOMATIC);
            } else {
                doc.resizeImage(UnitValue(large, "px"), null, 72, ResampleMethod.BICUBICAUTOMATIC);
            }
            doc.resizeCanvas(large, large, AnchorPosition.MIDDLECENTER);
            setJPEGQuality(jpegSaveOptions, 70); // Adjust quality to target size 70 KB
            doc.saveAs(saveImgLarge, jpegSaveOptions, true, Extension.LOWERCASE);

            // Normal
            doc.resizeImage(UnitValue(normal, "px"), UnitValue(normal, "px"), 72, ResampleMethod.BICUBICAUTOMATIC);
            setJPEGQuality(jpegSaveOptions, 50); // Adjust quality to target size 50 KB
            doc.saveAs(saveImgNormal, jpegSaveOptions, true, Extension.LOWERCASE);

            // Thumbnail
            doc.resizeImage(UnitValue(thumbnail, "px"), UnitValue(thumbnail, "px"), 72, ResampleMethod.BICUBICAUTOMATIC);
            setJPEGQuality(jpegSaveOptions, 20); // Adjust quality to target size 20 KB
            doc.saveAs(saveImgThumbnail, jpegSaveOptions, true, Extension.LOWERCASE);

            doc.close(SaveOptions.DONOTSAVECHANGES);
        } catch (err) {
            errors.push(fileList[i].name);
        }
    }
}


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!");
}

I tried the above code (any many variations). I am expecting it to resize and compress images.

Share Improve this question asked Feb 14 at 18:36 DecentDecent 9 2
  • Thank you. I am not sure what I asked wrong to get downvoted instead of corrected. Seems people downvote if they don't know the answer, but I am not sure. Anyways, I appreciate the feedback. I will continue on trying to get it. I just need to file sizes to be under a certain size of kb. – Decent Commented Feb 14 at 20:57
  • I am ok with people telling me I am wrong, just wish they would tell me why or how I am wrong so I won't do it again. I appreciate it 'K J'. – Decent Commented Feb 14 at 21:34
Add a comment  | 

1 Answer 1

Reset to default -1

I don't know why this was down voted.

I suspect your script isn't working as the file saved isn't being properly released. I've adjusted the loop to save out iterative versions and you can see for yourself:

// Set jpeg save options with quality adjustments
function setJPEGQuality(saveOptions, targetSizeKB) 
{
    var quality = 12; // Start with maximum quality
    //var tempFile = new File("~/Desktop/temp.jpg");
    
    do {
        saveOptions.quality = quality;
        var f = "~/Desktop/temp_" + quality + ".jpg";
        var tempFile = new File(f);
        doc.saveAs(tempFile, saveOptions, true, Extension.LOWERCASE);

        var fileSize = tempFile.length / 1024; // Convert bytes to KB

        if (fileSize > targetSizeKB) 
        {
            alert("Needs to be smaller:\n" + fileSize + " " + targetSizeKB + "\n" + saveOptions.quality);
            quality -= 1; // Reduce quality to decrease file size
        } 
        else 
        {
            alert("quality: " + quality);
            break; // Exit the loop if target size is met
        }
    } while (quality > 0);

    tempFile.remove(); // Clean up the temp file
}
发布评论

评论列表(0)

  1. 暂无评论