Skip to main content
Participating Frequently
June 12, 2021
Answered

Save for Web with Month & Day Script?

  • June 12, 2021
  • 7 replies
  • 7484 views

Hello:

 

Searching hasn't found this needed workflow.  
Not sure this is the most efficient as it's legacy, but I use Save for Web to output needed images daily. I'd like the "save as" dialog to include month & day followed by and underscore

(ex. 0611_) already included in the file name. It would output a JPG, Quality 50%, Optimized, Convert to sRGB. 

Not sure this is possible, but would appreciate any help/direction given.


Thanks!

This topic has been closed for replies.
Correct answer Stephen Marsh

I like how this script is coming together, it is giving me the opportunity to implement some new ideas. This 1.4 version is back to a single script, there is no need for a two part script.

 

Hold down SHIFT when running the script to set the save location to the preference file.

Run the script WITHOUT shift to save to the location saved in the preference file.

 

There is now an error check if the preference file exists (it does not check if the content is valid). I have noticed that if one cancels the script while selecting the file path, it will leave the content of the preference file blank and or remove the previous file path.

 

/*

Export S4W sRGB JPG MMDD_ Prefix - SHIFT Key.jsx
Stephen Marsh, 23rd June 2021 - v1.4

Save for Web with Month & Day Script?
https://community.adobe.com/t5/photoshop/save-for-web-with-month-amp-day-script/td-p/12108287

Features:
    * Run the script with the shift key depressed to set the save path to the preference file
    * Run the script without the shift key depressed to save the JPEG file
    * Previous save location written/read from a custom preference text file '_MMDD_Pref-File.txt' in the user home folder
    * Check for overwriting an existing JPEG file, validation requires that the file name contains spaces, not hyphens
    * Conditional conversion to sRGB ICC profile
    * Removal of photoshop:DocumentAncestors metadata that may build up and bloat the template
    * NOTE: JPEG Quality value = 50%

*/

#target photoshop

main();

function main() {

//////// HOLD THE SHIFT KEY DOWN TO SET THE FOLDER PATH ////////
    if (ScriptUI.environment.keyboardState.shiftKey) {

        // Set the save folder path
        var prefFileValue = Folder.selectDialog('Select a folder to save the JPEG image to...');

        // Write the last save path preference file in the user home folder
        var prefFile = new File('~/_MMDD-Script_Pref-File.txt');
        // Write the directory path to the pref file
        // r = read mode | w = write mode | a = append | e = edit
        prefFile.open('w');
        prefFile.write(prefFileValue.fsName);
        prefFile.close();
        prefFile.encoding = 'UTF-8';
        // LineFeed options
        // prefFile.lineFeed = "Unix";
        // prefFile.lineFeed = "Windows";
        // prefFile.lineFeed = "Macintosh";
        alert('Save location set to:' + '\r' + prefFileValue.fsName);

////////// IF THE SHIFT KEY WAS NOT HELD DOWN, RUN THE MAIN SCRIPT //////////
    } else {

        if (app.documents.length !== 0) {

            if (File('~/_MMDD-Script_Pref-File.txt').exists && File('~/_MMDD-Script_Pref-File.txt').length > 0) {

                // Date & time variables, this script only uses the month and date (day) variables
                // community.adobe.com/t5/photoshop/photoshop-script-save-as-jpg-with-current-date-and-time/td-p/11115756
                var dateObj = new Date();
                //var year = dateObj.getFullYear().toString().substr(-2);
                var month = ("0" + (dateObj.getMonth() + 1)).slice(-2);
                var date = ("0" + dateObj.getDate()).slice(-2);
                //var time = dateObj.getTime();
                //var hours = dateObj.getHours();
                //var minutes = dateObj.getMinutes();
                //var seconds = dateObj.getSeconds();
                //var completeTime = hours.toString() + minutes.toString() + seconds.toString();
                //var completeDate = year.toString() + month.toString() + date.toString();

                // MMDD_ prefix
                var mmDDprefix = month.toString() + date.toString() + '_';

                // Set the active document variable
                var doc = app.activeDocument;

                // Name options
                // Depending on S4W filename compatibility settings, you may need to replace the space with a hyphen:
                // .replace(/ /g, '-');
                var docName = doc.name.replace(/\.[^\.]+$/, '').replace(/ /g, ' '); // See above
                var docNameInput = prompt('Enter a filename (without extension):', mmDDprefix + docName);
                var docNameOutput = docNameInput.replace(/\.[^\.]+$/, '');

                // Read the last save path preference file in the user home folder
                var prefFileRead = File('~/_MMDD-Script_Pref-File.txt');
                // Open the pref file: r = read mode | w = write mode | a = append | e = edit
                prefFileRead.open('r');
                // Read the value for the save path
                var prefFileValue = prefFileRead.readln();
                //alert('Preference file path:' + '\r' + prefFileValue);

                // JPEG S4W Options
                function SaveForWeb(saveFileJPEG) {
                    var sfwOptions = new ExportOptionsSaveForWeb();
                    sfwOptions.format = SaveDocumentType.JPEG;
                    sfwOptions.includeProfile = true;
                    sfwOptions.optimized = true;
                    sfwOptions.quality = 50;
                    doc.exportDocument(saveFileJPEG, ExportType.SAVEFORWEB, sfwOptions);
                }

                // File path & naming
                var saveFileJPEG = new File(prefFileValue + '/' + docNameOutput + '.jpg');

                // Confirm overwrite - name validation is dependent on SFW filename compatibility settings
                if (saveFileJPEG.exists) {
                    // true = 'No' as default active button
                    if (!confirm("File exists, overwrite: Yes or No?", true))
                        // Optional - swap the throw alert for " throw null; " to remove the alert message
                        throw alert("Script cancelled!");
                }

                // Conditional colour space handling
                // Check for untagged image
                if (doc.colorProfileType === ColorProfile.NONE) {
                    // alert("Untagged");
                    // Call the function
                    sRGBprocessing();

                    // Check for any profile name which does not contain sRGB
                } else if (doc.colorProfileName.match(/\bsRGB\b/) === null) {
                    // else if (doc.colorProfileName !== "sRGB IEC61966-2.1")
                    // alert("sRGB = False");
                    // Call the function
                    sRGBprocessing();

                    // Check for any profile name which contains sRGB
                } else if (doc.colorProfileName.match(/\bsRGB\b/) !== null) {
                    // else if (doc.colorProfileName === "sRGB IEC61966-2.1")
                    // alert("sRGB = True");
                    // Export
                    SaveForWeb(saveFileJPEG);
                } else { }

                function sRGBprocessing() {
                    // Convert to profile - sRGB (profile, intent, BPC, dither)
                    doc.convertProfile("sRGB IEC61966-2.1", Intent.RELATIVECOLORIMETRIC, true, false);
                    // Export
                    SaveForWeb(saveFileJPEG);
                    // Delete convert to sRGB history step
                    deleteLastHistoryStep();

                    function deleteLastHistoryStep() {
                        var iddelete = stringIDToTypeID("delete");
                        var desc1497 = new ActionDescriptor();
                        var idnull = stringIDToTypeID("null");
                        var ref22 = new ActionReference();
                        var idhistoryState = stringIDToTypeID("historyState");
                        var idordinal = stringIDToTypeID("ordinal");
                        var idlast = stringIDToTypeID("last");
                        ref22.putEnumerated(idhistoryState, idordinal, idlast);
                        desc1497.putReference(idnull, ref22);
                        executeAction(iddelete, desc1497, DialogModes.NO);
                    }
                }

                // As this is a template, remove photoshop:DocumentAncestors metadata that may build up and bloat the file
                // https://prepression.blogspot.com/2017/06/metadata-bloat-photoshopdocumentancestors.html
                deleteDocumentAncestorsMetadata();

                function deleteDocumentAncestorsMetadata() {
                    // https://forums.adobe.com/message/8456985#8456985
                    if (ExternalObject.AdobeXMPScript === undefined) ExternalObject.AdobeXMPScript = new ExternalObject("lib:AdobeXMPScript");
                    var xmp = new XMPMeta(activeDocument.xmpMetadata.rawData);
                    xmp.deleteProperty(XMPConst.NS_PHOTOSHOP, "DocumentAncestors");
                    app.activeDocument.xmpMetadata.rawData = xmp.serialize();
                }

                // Optional end of script message, comment out or remove as required
                alert(docNameOutput + '.jpg' + '\r' + 'Saved to:' + '\r\r' + prefFileValue);

                // Optional end of script alert, comment out or remove as required
                // app.beep();

            } else {
                app.beep();
                alert("Save location doesn't exist! \r First hold down SHIFT while executing this script, then run the script again WITHOUT the shift key being held");
            }
        } else {
            app.beep();
            alert('You must have a document open to use this script!');

        }
    }
}

 

 

7 replies

Stephen Marsh
Stephen MarshCorrect answer
Community Expert
June 23, 2021

I like how this script is coming together, it is giving me the opportunity to implement some new ideas. This 1.4 version is back to a single script, there is no need for a two part script.

 

Hold down SHIFT when running the script to set the save location to the preference file.

Run the script WITHOUT shift to save to the location saved in the preference file.

 

There is now an error check if the preference file exists (it does not check if the content is valid). I have noticed that if one cancels the script while selecting the file path, it will leave the content of the preference file blank and or remove the previous file path.

 

/*

Export S4W sRGB JPG MMDD_ Prefix - SHIFT Key.jsx
Stephen Marsh, 23rd June 2021 - v1.4

Save for Web with Month & Day Script?
https://community.adobe.com/t5/photoshop/save-for-web-with-month-amp-day-script/td-p/12108287

Features:
    * Run the script with the shift key depressed to set the save path to the preference file
    * Run the script without the shift key depressed to save the JPEG file
    * Previous save location written/read from a custom preference text file '_MMDD_Pref-File.txt' in the user home folder
    * Check for overwriting an existing JPEG file, validation requires that the file name contains spaces, not hyphens
    * Conditional conversion to sRGB ICC profile
    * Removal of photoshop:DocumentAncestors metadata that may build up and bloat the template
    * NOTE: JPEG Quality value = 50%

*/

#target photoshop

main();

function main() {

//////// HOLD THE SHIFT KEY DOWN TO SET THE FOLDER PATH ////////
    if (ScriptUI.environment.keyboardState.shiftKey) {

        // Set the save folder path
        var prefFileValue = Folder.selectDialog('Select a folder to save the JPEG image to...');

        // Write the last save path preference file in the user home folder
        var prefFile = new File('~/_MMDD-Script_Pref-File.txt');
        // Write the directory path to the pref file
        // r = read mode | w = write mode | a = append | e = edit
        prefFile.open('w');
        prefFile.write(prefFileValue.fsName);
        prefFile.close();
        prefFile.encoding = 'UTF-8';
        // LineFeed options
        // prefFile.lineFeed = "Unix";
        // prefFile.lineFeed = "Windows";
        // prefFile.lineFeed = "Macintosh";
        alert('Save location set to:' + '\r' + prefFileValue.fsName);

////////// IF THE SHIFT KEY WAS NOT HELD DOWN, RUN THE MAIN SCRIPT //////////
    } else {

        if (app.documents.length !== 0) {

            if (File('~/_MMDD-Script_Pref-File.txt').exists && File('~/_MMDD-Script_Pref-File.txt').length > 0) {

                // Date & time variables, this script only uses the month and date (day) variables
                // community.adobe.com/t5/photoshop/photoshop-script-save-as-jpg-with-current-date-and-time/td-p/11115756
                var dateObj = new Date();
                //var year = dateObj.getFullYear().toString().substr(-2);
                var month = ("0" + (dateObj.getMonth() + 1)).slice(-2);
                var date = ("0" + dateObj.getDate()).slice(-2);
                //var time = dateObj.getTime();
                //var hours = dateObj.getHours();
                //var minutes = dateObj.getMinutes();
                //var seconds = dateObj.getSeconds();
                //var completeTime = hours.toString() + minutes.toString() + seconds.toString();
                //var completeDate = year.toString() + month.toString() + date.toString();

                // MMDD_ prefix
                var mmDDprefix = month.toString() + date.toString() + '_';

                // Set the active document variable
                var doc = app.activeDocument;

                // Name options
                // Depending on S4W filename compatibility settings, you may need to replace the space with a hyphen:
                // .replace(/ /g, '-');
                var docName = doc.name.replace(/\.[^\.]+$/, '').replace(/ /g, ' '); // See above
                var docNameInput = prompt('Enter a filename (without extension):', mmDDprefix + docName);
                var docNameOutput = docNameInput.replace(/\.[^\.]+$/, '');

                // Read the last save path preference file in the user home folder
                var prefFileRead = File('~/_MMDD-Script_Pref-File.txt');
                // Open the pref file: r = read mode | w = write mode | a = append | e = edit
                prefFileRead.open('r');
                // Read the value for the save path
                var prefFileValue = prefFileRead.readln();
                //alert('Preference file path:' + '\r' + prefFileValue);

                // JPEG S4W Options
                function SaveForWeb(saveFileJPEG) {
                    var sfwOptions = new ExportOptionsSaveForWeb();
                    sfwOptions.format = SaveDocumentType.JPEG;
                    sfwOptions.includeProfile = true;
                    sfwOptions.optimized = true;
                    sfwOptions.quality = 50;
                    doc.exportDocument(saveFileJPEG, ExportType.SAVEFORWEB, sfwOptions);
                }

                // File path & naming
                var saveFileJPEG = new File(prefFileValue + '/' + docNameOutput + '.jpg');

                // Confirm overwrite - name validation is dependent on SFW filename compatibility settings
                if (saveFileJPEG.exists) {
                    // true = 'No' as default active button
                    if (!confirm("File exists, overwrite: Yes or No?", true))
                        // Optional - swap the throw alert for " throw null; " to remove the alert message
                        throw alert("Script cancelled!");
                }

                // Conditional colour space handling
                // Check for untagged image
                if (doc.colorProfileType === ColorProfile.NONE) {
                    // alert("Untagged");
                    // Call the function
                    sRGBprocessing();

                    // Check for any profile name which does not contain sRGB
                } else if (doc.colorProfileName.match(/\bsRGB\b/) === null) {
                    // else if (doc.colorProfileName !== "sRGB IEC61966-2.1")
                    // alert("sRGB = False");
                    // Call the function
                    sRGBprocessing();

                    // Check for any profile name which contains sRGB
                } else if (doc.colorProfileName.match(/\bsRGB\b/) !== null) {
                    // else if (doc.colorProfileName === "sRGB IEC61966-2.1")
                    // alert("sRGB = True");
                    // Export
                    SaveForWeb(saveFileJPEG);
                } else { }

                function sRGBprocessing() {
                    // Convert to profile - sRGB (profile, intent, BPC, dither)
                    doc.convertProfile("sRGB IEC61966-2.1", Intent.RELATIVECOLORIMETRIC, true, false);
                    // Export
                    SaveForWeb(saveFileJPEG);
                    // Delete convert to sRGB history step
                    deleteLastHistoryStep();

                    function deleteLastHistoryStep() {
                        var iddelete = stringIDToTypeID("delete");
                        var desc1497 = new ActionDescriptor();
                        var idnull = stringIDToTypeID("null");
                        var ref22 = new ActionReference();
                        var idhistoryState = stringIDToTypeID("historyState");
                        var idordinal = stringIDToTypeID("ordinal");
                        var idlast = stringIDToTypeID("last");
                        ref22.putEnumerated(idhistoryState, idordinal, idlast);
                        desc1497.putReference(idnull, ref22);
                        executeAction(iddelete, desc1497, DialogModes.NO);
                    }
                }

                // As this is a template, remove photoshop:DocumentAncestors metadata that may build up and bloat the file
                // https://prepression.blogspot.com/2017/06/metadata-bloat-photoshopdocumentancestors.html
                deleteDocumentAncestorsMetadata();

                function deleteDocumentAncestorsMetadata() {
                    // https://forums.adobe.com/message/8456985#8456985
                    if (ExternalObject.AdobeXMPScript === undefined) ExternalObject.AdobeXMPScript = new ExternalObject("lib:AdobeXMPScript");
                    var xmp = new XMPMeta(activeDocument.xmpMetadata.rawData);
                    xmp.deleteProperty(XMPConst.NS_PHOTOSHOP, "DocumentAncestors");
                    app.activeDocument.xmpMetadata.rawData = xmp.serialize();
                }

                // Optional end of script message, comment out or remove as required
                alert(docNameOutput + '.jpg' + '\r' + 'Saved to:' + '\r\r' + prefFileValue);

                // Optional end of script alert, comment out or remove as required
                // app.beep();

            } else {
                app.beep();
                alert("Save location doesn't exist! \r First hold down SHIFT while executing this script, then run the script again WITHOUT the shift key being held");
            }
        } else {
            app.beep();
            alert('You must have a document open to use this script!');

        }
    }
}

 

 

Participating Frequently
June 23, 2021

Hey Stephen-That's a great solution to the workflow!

I'll load it up tomorrow and give it a go. I was too busy today to try out your other version. 

Thanks,

 

Rob

Stephen Marsh
Community Expert
June 30, 2021

@pandemicmonkee 

 

Is there a correct answer somewhere here?

Stephen Marsh
Community Expert
June 22, 2021

Please try these 1.3 versions.

 

Step 1:

Run the Step 1 script to write the desired save location to the log preference text file. This location will be used by the second script without offering a dialog for a save location. When you need a new save location, run the Step 1 script again.

 

 

/* 

Export S4W sRGB JPG MMDD_ Prefix - Step 1.jsx
Stephen Marsh, 23rd June 2021 - v1.3

Save for Web with Month & Day Script?
https://community.adobe.com/t5/photoshop/save-for-web-with-month-amp-day-script/td-p/12108287

///// Create the preference log file /////

*/

#target photoshop

// Set the save folder path
var docPath = Folder.selectDialog('Select a folder to save the JPEG image to...');

// Write the last save path preference file in the user home folder
var prefFile = new File('~/_MMDD-Script_Pref-File.pref');
// Write the directory path to the pref file
// r = read mode | w = write mode | a = append | e = edit
prefFile.open('w');
prefFile.write(docPath.fsName);
prefFile.close();
prefFile.encoding = 'UTF-8';
// LineFeed options
// prefFile.lineFeed = "Unix";
// prefFile.lineFeed = "Windows";
// prefFile.lineFeed = "Macintosh";
//alert('Preference file path:' + '\r' + docPath.fsName);

alert('Save location set to:' + '\r' + docPath.fsName);

 

 

Step 2:

Run the Step 2 script as required. When a new save location is required, run the Step 1 script again, then use the Step 2 script again until a new save location is required. Repeat as necessary.

 

 

/*

Export S4W sRGB JPG MMDD_ Prefix - Step 2.jsx
Stephen Marsh, 23rd June 2021 - v1.3

Save for Web with Month & Day Script?
https://community.adobe.com/t5/photoshop/save-for-web-with-month-amp-day-script/td-p/12108287

///// Main script to run after first setting the preference file /////

*/

#target photoshop

if (app.documents.length !== 0) {

    // Date & time variables, this script only uses the month and date (day) variables
    // community.adobe.com/t5/photoshop/photoshop-script-save-as-jpg-with-current-date-and-time/td-p/11115756
    var dateObj = new Date();
    var year = dateObj.getFullYear().toString().substr(-2);
    var month = ("0" + (dateObj.getMonth() + 1)).slice(-2);
    var date = ("0" + dateObj.getDate()).slice(-2);
    var time = dateObj.getTime();
    var hours = dateObj.getHours();
    var minutes = dateObj.getMinutes();
    var seconds = dateObj.getSeconds();
    var completeTime = hours.toString() + minutes.toString() + seconds.toString();
    var completeDate = year.toString() + month.toString() + date.toString();

    // MMDD_ prefix
    var mmDDprefix = month.toString() + date.toString() + '_';

    // Set the active document variable
    var doc = app.activeDocument;

    // Name options
    // Depending on S4W filename compatibility settings, you may need to replace the space with a hyphen:
    // .replace(/ /g, '-');
    var docName = doc.name.replace(/\.[^\.]+$/, '').replace(/ /g, ' '); // See above
    var docNameInput = prompt('Enter a filename (without extension):', mmDDprefix + docName);
    var docNameOutput = docNameInput.replace(/\.[^\.]+$/, '');

    // Preference File Step 1 - Read the last save path preference file in the user home folder
    // Pref file location
    var prefFileRead = File('~/_MMDD-Script_Pref-File.pref');
    // Open the pref file: r = read mode | w = write mode | a = append | e = edit
    var openPrefFile = prefFileRead.open('r');
    // Read the value for the save path
    var prefFileValue = prefFileRead.readln();
    //alert('Preference file path:' + '\r' + prefFileValue);

    // JPEG S4W Options
    function SaveForWeb(saveFileJPEG) {
        var sfwOptions = new ExportOptionsSaveForWeb();
        sfwOptions.format = SaveDocumentType.JPEG;
        sfwOptions.includeProfile = true;
        sfwOptions.optimized = true;
        sfwOptions.quality = 50;
        doc.exportDocument(saveFileJPEG, ExportType.SAVEFORWEB, sfwOptions);
    }

    // File path & naming
    var saveFileJPEG = new File(prefFileValue + '/' + docNameOutput + '.jpg');

    // Confirm overwrite - name validation is dependent on SFW filename compatibility settings
    if (saveFileJPEG.exists) {
        // true = 'No' as default active button
        if (!confirm("File exists, overwrite: Yes or No?", true))
            // Optional - swap the throw alert for " throw null; " to remove the alert message
            throw alert("Script cancelled!");
    }

    // Conditional colour space handling
    // Check for untagged image
    if (doc.colorProfileType === ColorProfile.NONE) {
        // alert("Untagged");
        // Call the function
        sRGBprocessing();

        // Check for any profile name which does not contain sRGB
    } else if (doc.colorProfileName.match(/\bsRGB\b/) === null) {
        // else if (doc.colorProfileName !== "sRGB IEC61966-2.1")
        // alert("sRGB = False");
        // Call the function
        sRGBprocessing();

        // Check for any profile name which contains sRGB
    } else if (doc.colorProfileName.match(/\bsRGB\b/) !== null) {
        // else if (doc.colorProfileName === "sRGB IEC61966-2.1")
        // alert("sRGB = True");
        // Export
        SaveForWeb(saveFileJPEG);
    } else { }

    function sRGBprocessing() {
        // Convert to profile - sRGB (profile, intent, BPC, dither)
        doc.convertProfile("sRGB IEC61966-2.1", Intent.RELATIVECOLORIMETRIC, true, false);
        // Export
        SaveForWeb(saveFileJPEG);
        // Delete convert to sRGB history step
        deleteLastHistoryStep();
        function deleteLastHistoryStep() {
            var iddelete = stringIDToTypeID("delete");
            var desc1497 = new ActionDescriptor();
            var idnull = stringIDToTypeID("null");
            var ref22 = new ActionReference();
            var idhistoryState = stringIDToTypeID("historyState");
            var idordinal = stringIDToTypeID("ordinal");
            var idlast = stringIDToTypeID("last");
            ref22.putEnumerated(idhistoryState, idordinal, idlast);
            desc1497.putReference(idnull, ref22);
            executeAction(iddelete, desc1497, DialogModes.NO);
        }
    }

    // As this is a template, remove photoshop:DocumentAncestors metadata that may build up and bloat the file
    // https://prepression.blogspot.com/2017/06/metadata-bloat-photoshopdocumentancestors.html
    deleteDocumentAncestorsMetadata();

    function deleteDocumentAncestorsMetadata() {
        // https://forums.adobe.com/message/8456985#8456985
        if (ExternalObject.AdobeXMPScript === undefined) ExternalObject.AdobeXMPScript = new ExternalObject("lib:AdobeXMPScript");
        var xmp = new XMPMeta(activeDocument.xmpMetadata.rawData);
        xmp.deleteProperty(XMPConst.NS_PHOTOSHOP, "DocumentAncestors");
        app.activeDocument.xmpMetadata.rawData = xmp.serialize();
    }

    // Optional end of script message, comment out or remove as required
    alert(docNameOutput + '.jpg' + '\r' + 'Saved to:' + '\r\r' + prefFileValue);

    // Optional end of script alert, comment out or remove as required
    // app.beep();

} else {

    alert('You must have a document open to use this script!');

}

 

 

NOTE: I have not set any error checking to test if the preference log file exists, or if it has content, or if the content is valid. Ensure that Step 1 is run at least once before running Step 2!

 

Participating Frequently
June 22, 2021

Great, thanks, Stephen. 
Yes, I'm only saving to one location each day, that being a dated folder, so after I select the location once, I don't need to select another anymore that day. 
I'll try and load this up tomorrow and test it out. 

Thanks again,

 

Rob

Stephen Marsh
Community Expert
June 22, 2021

If this is what you are looking for, is running two different scripts going to be painful? If yes, I might be able to get this into a single script that you can use a modifier key such as shift to action. That way if you hold down shift when running the action it will ask you to set the save path, otherwise running the script without the shift key will just run the save part.

Nancy OShea
Community Expert
June 14, 2021

Maybe I'm being daft but your operating system already does this automatically.  Each file has an associated date & time stamp.  You can also sort files by Date Modified or Date Created. See screenshot from Windows File Explorer.

 

 

Likewise, Dreamweaver has an option to show date & time stamp from the Files Panel (F8) so you can sort your assets accordingly.

 

Nancy O'Shea— Product User & Community Expert
Participating Frequently
June 15, 2021

Hi Nancy-My need isn't viewing metadata, it's writing it to the file name that's created. 
I'm just trying to automate the parts of the process that can be, to save some time and accuracy. 
After seeing what Stephen put together, I'm realizing I need to learn JavaScript! 🤔 🤔

Stephen Marsh
Community Expert
June 14, 2021

This 1.2 version will read/write to a prererence text file saved to the user home folder.

 

/* 

Export S4W sRGB JPG MMDD_ Prefix.jsx
Stephen Marsh, 14th June 2021 - v1.2

Save for Web with Month & Day Script?
https://community.adobe.com/t5/photoshop/save-for-web-with-month-amp-day-script/td-p/12108287

This script exports a Save for Web JPEG to a user selected-folder with a 'MMDD_' prefix

Features:
    * Previous save location written/read from a custom preference text file '_MMDD_Pref-File.pref' in the user home folder
    * Check for overwriting an existing file, validation requires that the file name contains spaces, not hyphens
    * Conditional conversion to sRGB ICC profile
    * Removal of photoshop:DocumentAncestors metadata that may build up and bloat the template
    * NOTE: JPEG Quality value = 50%

*/

#target photoshop

if (app.documents.length !== 0) {

    // Date & time variables, this script only uses the month and date (day) variables
    // community.adobe.com/t5/photoshop/photoshop-script-save-as-jpg-with-current-date-and-time/td-p/11115756
    var dateObj = new Date();
    var year = dateObj.getFullYear().toString().substr(-2);
    var month = ("0" + (dateObj.getMonth() + 1)).slice(-2);
    var date = ("0" + dateObj.getDate()).slice(-2);
    var time = dateObj.getTime();
    var hours = dateObj.getHours();
    var minutes = dateObj.getMinutes();
    var seconds = dateObj.getSeconds();
    var completeTime = hours.toString() + minutes.toString() + seconds.toString();
    var completeDate = year.toString() + month.toString() + date.toString();

    // MMDD_ prefix
    var mmDDprefix = month.toString() + date.toString() + '_';

    // Set the active document variable
    var doc = app.activeDocument;

    // Name options
    // Depending on S4W filename compatibility settings, you may need to replace the space with a hyphen:
    // .replace(/ /g, '-');
    var docName = doc.name.replace(/\.[^\.]+$/, '').replace(/ /g, ' '); // See above
    var docNameInput = prompt('Enter a filename (without extension):', mmDDprefix + docName);
    var docNameOutput = docNameInput.replace(/\.[^\.]+$/, '');

    // Preference File Step 1 - Read the last save path preference file in the user home folder
    // It's OK if the pref file doesn't exist in the first use 
    // Pref file location
    var prefFileRead = File('~/_MMDD-Script_Pref-File.pref');
    // Open the pref file: r = read mode | w = write mode | a = append | e = edit
    var openPrefFile = prefFileRead.open('r');
    // Read the value
    var prefFileValue = prefFileRead.readln();
    // Use the variable from the preference file for the save path
    //alert('Preference file path:' + '\r' + prefFileValue);
    var docPath = Folder.selectDialog('Select a folder to save the JPEG image to...', prefFileValue);

    // Preference File Step 2 - Write the last save path preference file in the user home folder
    var prefFile = new File('~/_MMDD-Script_Pref-File.pref');
    // Write the directory path to the pref file
    // r = read mode | w = write mode | a = append | e = edit
    prefFile.open('w');
    prefFile.write(docPath.fsName);
    prefFile.close();
    prefFile.encoding = 'UTF-8';
    // LineFeed options
    // prefFile.lineFeed = "Unix";
    // prefFile.lineFeed = "Windows";
    // prefFile.lineFeed = "Macintosh";
    //alert('Preference file path:' + '\r' + docPath.fsName);

    // JPEG S4W Options
    function SaveForWeb(saveFileJPEG) {
        var sfwOptions = new ExportOptionsSaveForWeb();
        sfwOptions.format = SaveDocumentType.JPEG;
        sfwOptions.includeProfile = true;
        sfwOptions.optimized = true;
        sfwOptions.quality = 50;
        doc.exportDocument(saveFileJPEG, ExportType.SAVEFORWEB, sfwOptions);
    }

    // File path & naming
    var saveFileJPEG = new File(docPath + '/' + docNameOutput + '.jpg');

    // Confirm overwrite - name validation is dependent on SFW filename compatibility settings
    if (saveFileJPEG.exists) {
        // true = 'No' as default active button
        if (!confirm("File exists, overwrite: Yes or No?", true))
            // Optional - swap the throw alert for " throw null; " to remove the alert message
            throw alert("Script cancelled!");
    }

    // Conditional colour space handling
    // Check for untagged image
    if (doc.colorProfileType === ColorProfile.NONE) {
        // alert("Untagged");
        // Call the function
        sRGBprocessing();

        // Check for any profile name which does not contain sRGB
    } else if (doc.colorProfileName.match(/\bsRGB\b/) === null) {
        // else if (doc.colorProfileName !== "sRGB IEC61966-2.1")
        // alert("sRGB = False");
        // Call the function
        sRGBprocessing();

        // Check for any profile name which contains sRGB
    } else if (doc.colorProfileName.match(/\bsRGB\b/) !== null) {
        // else if (doc.colorProfileName === "sRGB IEC61966-2.1")
        // alert("sRGB = True");
        // Export
        SaveForWeb(saveFileJPEG);
    } else { }

    function sRGBprocessing() {
        // Convert to profile - sRGB (profile, intent, BPC, dither)
        doc.convertProfile("sRGB IEC61966-2.1", Intent.RELATIVECOLORIMETRIC, true, false);
        // Export
        SaveForWeb(saveFileJPEG);
        // Delete convert to sRGB history step
        deleteLastHistoryStep();
        function deleteLastHistoryStep() {
            var iddelete = stringIDToTypeID("delete");
            var desc1497 = new ActionDescriptor();
            var idnull = stringIDToTypeID("null");
            var ref22 = new ActionReference();
            var idhistoryState = stringIDToTypeID("historyState");
            var idordinal = stringIDToTypeID("ordinal");
            var idlast = stringIDToTypeID("last");
            ref22.putEnumerated(idhistoryState, idordinal, idlast);
            desc1497.putReference(idnull, ref22);
            executeAction(iddelete, desc1497, DialogModes.NO);
        }
    }

    // As this is a template, remove photoshop:DocumentAncestors metadata that may build up and bloat the file
    // https://prepression.blogspot.com/2017/06/metadata-bloat-photoshopdocumentancestors.html
    deleteDocumentAncestorsMetadata();

    function deleteDocumentAncestorsMetadata() {
        // https://forums.adobe.com/message/8456985#8456985
        if (ExternalObject.AdobeXMPScript === undefined) ExternalObject.AdobeXMPScript = new ExternalObject("lib:AdobeXMPScript");
        var xmp = new XMPMeta(activeDocument.xmpMetadata.rawData);
        xmp.deleteProperty(XMPConst.NS_PHOTOSHOP, "DocumentAncestors");
        app.activeDocument.xmpMetadata.rawData = xmp.serialize();
    }

    // Optional end of script message, comment out or remove as required
    alert(docNameOutput + '.jpg' + '\r' + 'Saved to:' + '\r\r' + docPath.fsName);

    // Optional end of script alert, comment out or remove as required
    // app.beep();

} else {

    alert('You must have a document open to use this script!');

}

 

Participating Frequently
June 15, 2021

Awesome! Thanks again, Stephen!

Stephen Marsh
Community Expert
June 15, 2021

So, did the last save location written and read from the file work?

Stephen Marsh
Community Expert
June 14, 2021

Major changes in v1.1 from the original v1.0 code:

 

* Check for overwriting an existing file, validation requires that the file name contains spaces – not hyphens. If your S4W file naming compatibility settings are set to replace word spaces with hyphens, you can look in the code comments on how to change the code to also use hyphens: .replace(/ /g, '-');
 
* Conditional conversion to sRGB ICC profile. If the file is already tagged as sRGB, there will be no conversion. If the file is not tagged as sRGB, then the JPEG copy will be converted. If the file is untagged, the working RGB will be assumed for the source when converting.
 
I have tested the script, however, there are no guarantees or warranties, use at your own risk. Hope this helps!

 

/* 

Export S4W sRGB JPG MMDD_ Prefix.jsx
Stephen Marsh, 13th June 2021 - v1.1

Save for Web with Month & Day Script?
https://community.adobe.com/t5/photoshop/save-for-web-with-month-amp-day-script/td-p/12108287

This script exports a Save for Web JPEG to a user selected-folder with a 'MMDD_' prefix

Features:
   * Check for overwriting an existing file, validation requires that the file name contains spaces, not hyphens
   * Conditional conversion to sRGB ICC profile
   * Removal of photoshop:DocumentAncestors metadata that may build up and bloat the template
   * NOTE: JPEG Quality value = 50%

*/

#target photoshop

if (app.documents.length !== 0) {

    // Date & time variables, this script only uses the month and date (day) variables
    // community.adobe.com/t5/photoshop/photoshop-script-save-as-jpg-with-current-date-and-time/td-p/11115756
    var dateObj = new Date();
    var year = dateObj.getFullYear().toString().substr(-2);
    var month = ("0" + (dateObj.getMonth() + 1)).slice(-2);
    var date = ("0" + dateObj.getDate()).slice(-2);
    var time = dateObj.getTime();
    var hours = dateObj.getHours();
    var minutes = dateObj.getMinutes();
    var seconds = dateObj.getSeconds();
    var completeTime = hours.toString() + minutes.toString() + seconds.toString();
    var completeDate = year.toString() + month.toString() + date.toString();

    // MMDD_ prefix
    var mmDDprefix = month.toString() + date.toString() + '_';

    // Set the active document variable
    var doc = app.activeDocument;

    // Name & path related options
    // Depending on S4W filename compatibility settings, you may need to replace the space with a hyphen:
    // .replace(/ /g, '-');
    var docName = doc.name.replace(/\.[^\.]+$/, '').replace(/ /g, ' '); // See above
    var docNameInput = prompt('Enter a filename (without extension):', mmDDprefix + docName);
    var docNameOutput = docNameInput.replace(/\.[^\.]+$/, '');
    var docPath = Folder.selectDialog('Select a folder to save the JPEG image to...');

    // JPEG S4W Options
    function SaveForWeb(saveFileJPEG) {
        var sfwOptions = new ExportOptionsSaveForWeb();
        sfwOptions.format = SaveDocumentType.JPEG;
        sfwOptions.includeProfile = true;
        sfwOptions.optimized = true;
        sfwOptions.quality = 50;
        doc.exportDocument(saveFileJPEG, ExportType.SAVEFORWEB, sfwOptions);
    }

    // File path & naming
    var saveFileJPEG = new File(docPath + '/' + docNameOutput + '.jpg');

    // Confirm overwrite - name validation is dependent on SFW filename compatibility settings
    if (saveFileJPEG.exists) {
        // true = 'No' as default active button
        if (!confirm("File exists, overwrite: Yes or No?", true))
            // Optional - swap the throw alert for " throw null; " to remove the alert message
            throw alert("Script cancelled!");
    }

    // Conditional colour space handling
    // Check for untagged image
    if (doc.colorProfileType === ColorProfile.NONE) {
        // alert("Untagged");
        // Call the function
        sRGBprocessing();

        // Check for any profile name which does not contain sRGB
    } else if (doc.colorProfileName.match(/\bsRGB\b/) === null) {
        // else if (doc.colorProfileName !== "sRGB IEC61966-2.1")
        // alert("sRGB = False");
        // Call the function
        sRGBprocessing();

        // Check for any profile name which contains sRGB
    } else if (doc.colorProfileName.match(/\bsRGB\b/) !== null) {
        // else if (doc.colorProfileName === "sRGB IEC61966-2.1")
        // alert("sRGB = True");
        // Export
        SaveForWeb(saveFileJPEG);
    } else { }

    function sRGBprocessing() {
        // Convert to profile - sRGB (profile, intent, BPC, dither)
        doc.convertProfile("sRGB IEC61966-2.1", Intent.RELATIVECOLORIMETRIC, true, false);
        // Export
        SaveForWeb(saveFileJPEG);
        // Delete convert to sRGB history step
        deleteLastHistoryStep();
        function deleteLastHistoryStep() {
            var iddelete = stringIDToTypeID("delete");
            var desc1497 = new ActionDescriptor();
            var idnull = stringIDToTypeID("null");
            var ref22 = new ActionReference();
            var idhistoryState = stringIDToTypeID("historyState");
            var idordinal = stringIDToTypeID("ordinal");
            var idlast = stringIDToTypeID("last");
            ref22.putEnumerated(idhistoryState, idordinal, idlast);
            desc1497.putReference(idnull, ref22);
            executeAction(iddelete, desc1497, DialogModes.NO);
        }
    }

    // As this is a template, remove photoshop:DocumentAncestors metadata that may build up and bloat the file
    // https://prepression.blogspot.com/2017/06/metadata-bloat-photoshopdocumentancestors.html
    deleteDocumentAncestorsMetadata();

    function deleteDocumentAncestorsMetadata() {
        // https://forums.adobe.com/message/8456985#8456985
        if (ExternalObject.AdobeXMPScript === undefined) ExternalObject.AdobeXMPScript = new ExternalObject("lib:AdobeXMPScript");
        var xmp = new XMPMeta(activeDocument.xmpMetadata.rawData);
        xmp.deleteProperty(XMPConst.NS_PHOTOSHOP, "DocumentAncestors");
        app.activeDocument.xmpMetadata.rawData = xmp.serialize();
    }

    // Optional end of script message, comment out or remove as required
    alert(docNameOutput + '.jpg' + '\r' + 'Saved to:' + '\r\r' + docPath.fsName);

    // Optional end of script alert, comment out or remove as required
    // app.beep();

} else {

    alert('You must have a document open to use this script!');

}

 

Participating Frequently
June 14, 2021

Great! Thanks, Stephen!

Stephen Marsh
Community Expert
June 14, 2021

Where does the script prompt to select a save folder default to, if not the last used folder?

 

I have tested in CC2021 on both Mac (Big Sur) and Widows (10) and the previous directory used in the script is used, however, I'm not doing anything else in between.

 

What OS/Version are you using? 

 

What version of Photoshop?

 

I'll need to think about this. Presumably you can't use the template.psd location. The save folder is not static, you therefore need a prompt to manually select the save folder, yes? So I'd suggest that you still would use a prompt, it is just that the prompt would default to the last saved location, which still gives you flexibility to change the location if needed.

 

Stephen Marsh
Community Expert
June 12, 2021

Try this v1.0 script.

 

Please note:

 

* Existing files of the same name will be overwritten without warning (I can't get the code to work to verify, perhaps somebody else with scripting knowledge can help?)

 

* A prompt will be offered for you to fine tune the filename, by default it will prefix the MMDD_ before the existing document name (don't use any file extensions).

 

* A separate window will then open asking where to save the file, no default path to a specific folder is provided .

 

* photoshop:DocumentAncestors metadata that may accumulate in the template is removed.

 

 

/* 

Save for Web with Month & Day Script?
https://community.adobe.com/t5/photoshop/save-for-web-with-month-amp-day-script/td-p/12108287

This script exports a Save for Web JPEG to a user selected-folder with a MMDD_ prefix

!!! ATTENTION: Any files with the same name will be overwritten without warning !!!

Export S4W JPG MMDD_ Prefix.jsx
 
Stephen Marsh, 12th June 2021 - v1.0

*/

#target photoshop

if (app.documents.length !== 0) {

    // Date & time variables
    // community.adobe.com/t5/photoshop/photoshop-script-save-as-jpg-with-current-date-and-time/td-p/11115756
    var dateObj = new Date();
    var year = dateObj.getFullYear().toString().substr(-2);
    var month = ("0" + (dateObj.getMonth() + 1)).slice(-2);
    var date = ("0" + dateObj.getDate()).slice(-2);
    var time = dateObj.getTime();
    var hours = dateObj.getHours();
    var minutes = dateObj.getMinutes();
    var seconds = dateObj.getSeconds();
    var completeTime = hours.toString() + minutes.toString() + seconds.toString();
    var completeDate = year.toString() + month.toString() + date.toString();

    // MMDD_ prefix
    var mmDDprefix = month.toString() + date.toString() + '_';

    // Set the active document variable
    var doc = app.activeDocument;

    // Name & path related options
    var docName = doc.name.replace(/\.[^\.]+$/, '');
    var docNameInput = prompt('Enter a filename (without extension):', mmDDprefix + docName);
    var docNameOutput = docNameInput.replace(/\.[^\.]+$/, '');
    var docPath = Folder.selectDialog('Select a folder to save the JPEG image to...');

    // JPEG S4W Options
    function SaveForWeb(saveFileJPEG) {
        var sfwOptions = new ExportOptionsSaveForWeb();
        sfwOptions.format = SaveDocumentType.JPEG;
        sfwOptions.includeProfile = true;
        sfwOptions.interlaced = 0;
        sfwOptions.optimized = true;
        sfwOptions.quality = 50;
        doc.exportDocument(saveFileJPEG, ExportType.SAVEFORWEB, sfwOptions);
    }

    // File path & naming
    var saveFileJPEG = new File(docPath + '/' + docNameOutput + '.jpg');

    // Convert to sRGB
    doc.convertProfile("sRGB IEC61966-2.1", Intent.RELATIVECOLORIMETRIC, true, false);

    // Export
    SaveForWeb(saveFileJPEG);

    // Delete last history step (sRGB conversion)
    var iddelete = stringIDToTypeID("delete");
    var desc1497 = new ActionDescriptor();
    var idnull = stringIDToTypeID("null");
    var ref22 = new ActionReference();
    var idhistoryState = stringIDToTypeID("historyState");
    var idordinal = stringIDToTypeID("ordinal");
    var idlast = stringIDToTypeID("last");
    ref22.putEnumerated(idhistoryState, idordinal, idlast);
    desc1497.putReference(idnull, ref22);
    executeAction(iddelete, desc1497, DialogModes.NO);

    // As this is a template, remove photoshop:DocumentAncestors metadata that may build up and bloat the file
    // https://prepression.blogspot.com/2017/06/metadata-bloat-photoshopdocumentancestors.html
    deleteDocumentAncestorsMetadata();

    function deleteDocumentAncestorsMetadata() {
        // https://forums.adobe.com/message/8456985#8456985
        if (ExternalObject.AdobeXMPScript === undefined) ExternalObject.AdobeXMPScript = new ExternalObject("lib:AdobeXMPScript");
        var xmp = new XMPMeta(activeDocument.xmpMetadata.rawData);
        xmp.deleteProperty(XMPConst.NS_PHOTOSHOP, "DocumentAncestors");
        app.activeDocument.xmpMetadata.rawData = xmp.serialize();
    }

    // Optional end of script message
    alert(docNameOutput + '.jpg' + '\r' + 'Saved to:' + '\r' + '\r' + docPath.fsName);

} else {
    alert('You must have a document open to use this script!');
}

 

 

 

Downloading and Installing Adobe Scripts

 

Participating Frequently
June 12, 2021

Hey, thanks Stephen! Much appreciated!

I'll try it out tomorrow.

 

-Rob

Stephen Marsh
Community Expert
June 13, 2021

Please let me know how it goes...

 

I found the issue with the code that checks if a file of the existing name exists, the code was fine, however my S4W settings had inexplicably changed to use a setting with OS compatibility to replace word spaces with hyphens, while my code was expecting word spaces.

 

If your filenames use hyphens instead of word spaces, the code is easily changed by modifying one character.

 

I have a new 1.1 code version ready if there are no major changes required.

 

Stephen Marsh
Community Expert
June 12, 2021

Where in the filename? At the beginning? Do you need a dialog to possibly refine the rename, or is it simply enough to export the file automatically including the prefix MMDD_ without any window popping up? Where to save to? Do you want a prompt? To the source folder of the current open/saved file? What if the source file is not saved?

Participating Frequently
June 12, 2021

Hi:

 

Yes, I'll need to add some other file info before saving, which would be after date and underscore (0611_Subject.jpg)

 

Thanks!

Participating Frequently
June 12, 2021

Just to confirm before I complete the script:

 

(1) Save location:

Are you happy to have a prompt appear so that you can manually select the location to save the file? If so, should there be a default location where the save location defaults to, such as your Documents folder? Do you have a different requirement?

 

(2) Filename:

If the template file is named "my_Template.psd" and the prefix is "MMDD_" and the default name produced by the script is "MMDD_myTemplate.jpg" is there any need to edit the filename, or can the script directly save this filename without any interaction? If you do need to edit the name, what sort of manual edits are you making and could these possibly be performed by the script as well? For example, if you were saving the JPG into a folder named after a specific project, the script could use the folder name as part of the saved file name.


I save the image into a dated folder, so that would be the default folder to save to. I add a one or two word description of the subject matter. Could the you mimic the dated folder to create the date in the file name? Just curious if that's possible. I really appreciate your help with this!