Skip to main content
matt.cortright@gmail.com
Participant
April 22, 2017
Answered

automate save as or export with sequential file names

  • April 22, 2017
  • 8 replies
  • 12644 views

Hi, I have a script that does some basic color manipulates within a selection.  I will run this script thousands of times to produce my graphic.  I would like to export a copy of my working file each time I run this script so that I can compile each step into an animation.  Naming the files manually each time the action is run would be really tedious and time consuming.

I've been reading about batch actions and integrating those file naming options, but I seem to be going in circles without any results.  Could someone point me in the right direction please?

    This topic has been closed for replies.
    Correct answer c.pfaffenbichler

    Check out this thread: Progressive Save As New Jpeg

    8 replies

    Stephen Marsh
    Community Expert
    Community Expert
    January 18, 2021
    // https://forums.adobe.com/message/4453915#4453915
    #target photoshop
    main();
    function main(){
    if(!documents.length) return;
    var Name = app.activeDocument.name.replace(/\.[^\.]+$/, '');
    try{
    var savePath = activeDocument.path;
    }catch(e){
        alert("You must save this document first!");
        }
    var fileList= savePath.getFiles(Name +"*.psd").sort().reverse();
    var Suffix = 0;
    if(fileList.length){
        Suffix = Number(fileList[0].name.replace(/\.[^\.]+$/, '').match(/\d+$/));
    }
    Suffix= zeroPad(Suffix + 1, 3);
    var saveFile = File(savePath + "/" + Name + "_" + Suffix + ".psd");
    SavePSD(saveFile);
    }
    function SavePSD(saveFile){   
    // http://jongware.mit.edu/pscs5js_html/psjscs5/pc_PhotoshopSaveOptions.html
    psdSaveOptions = new PhotoshopSaveOptions();   
    psdSaveOptions.embedColorProfile = true;   
    psdSaveOptions.alphaChannels = true;    
    psdSaveOptions.layers = true;
    psdSaveOptions.annotations = true;
    psdSaveOptions.spotColors = true;
    activeDocument.saveAs(saveFile, psdSaveOptions, true, Extension.LOWERCASE);   
    }; 
    function zeroPad(n, s) { 
       n = n.toString(); 
       while (n.length < s)  n = '0' + n; 
       return n; 
    };
    Stephen Marsh
    Community Expert
    Community Expert
    January 18, 2021
    // Save PNG next to PSD (Incremental numbers)
    
    #target photoshop
    
    var savePSD    = false; // If set true the psd document is saved every time the script runs...
    var folderName = ' (Frames)';
    
    try {
    
      var doc   = app.activeDocument;
    	var fileExists = false;
    	
    	try { if ( savePSD ) doc.save(); } catch(e){}
    	
    	try {
    		fileExists = doc.path;
    	}
    	catch(e){
    		var idsave = charIDToTypeID( "save" );
    		var desc50 = new ActionDescriptor();
    		var idIn = charIDToTypeID( "In  " );
    		desc50.putPath( idIn, new File( Folder.desktop.fullName ) );
    		var idDocI = charIDToTypeID( "DocI" );
    		desc50.putInteger( idDocI, 196 );
    		var idsaveStage = stringIDToTypeID( "saveStage" );
    		var idsaveStageType = stringIDToTypeID( "saveStageType" );
    		var idsaveSucceeded = stringIDToTypeID( "saveSucceeded" );
    		desc50.putEnumerated( idsaveStage, idsaveStageType, idsaveSucceeded );
    		executeAction( idsave, desc50, DialogModes.ALL );
    		fileExists = doc.path;
    	}
    	
    	if ( fileExists ) {
    		saveNewVersion( doc );
    	}
    
    }
    catch( e ) {
      // remove comments below to see error for debugging
      // alert( e );
    }
    
    function saveNewVersion( doc, docName ) {
    
      var extension 	= '.png';
      var docName     = doc.name.substring(0, doc.name.lastIndexOf('.'));
      var docPath     = doc.path;
    	
      var outputPath = docPath + '/' + doc.name + folderName;
    	
      var outputFolder = new Folder( outputPath );
      if( !outputFolder.exists ) { outputFolder.create(); }
    	
      var verisonsList = outputFolder.getFiles( '*' + extension );
    	var versionsLength1 = verisonsList.length;
    	var number = getVersionNumber( docName, verisonsList );
    	
    	var filename = number + extension;
    	doc.exportDocument( File( outputPath + '/' + filename ), ExportType.SAVEFORWEB, exportOptions() );
      app.beep();
    
    }
    
    function getVersionNumber( docName, verisonsList ) {
    	
    	var number = 0;
    	for ( var i = 0; i < verisonsList.length; i++ ) {
    		
    		var file = verisonsList[i];
    		var fileName = File(file).displayName;
    		fileName = fileName.substring(0, fileName.lastIndexOf('.'));
    		
    		// Start looking for the version number if PSD filename contains doc name...
    		var versionNumber = fileName.match(/^[0-9]*/);
    		
    		if ( versionNumber ) {
    			versionNumber = parseInt( versionNumber ,10);
    			if ( number < versionNumber ) {
    				number = versionNumber;
    			}
    		}
    		
    	}
    	
    	return number + 1;
    	
    }
    
    function exportOptions() {
    	
    	var options = new ExportOptionsSaveForWeb();
    	
    	options.format = SaveDocumentType.PNG;
    	options.quality = 100;
    	
    	return options;
    	
    }
    
    Participating Frequently
    January 18, 2021

    This one does the job like I want, just that it saves the pictures in .PNG

    How can I change it to jpeg with quality 12?

    Stephen Marsh
    Community Expert
    Community Expert
    January 19, 2021

    That one is for both PSD and PNG versions.

     

    I presume that this would just be a case of removing the PSD option and swapping out PNG for JPEG?

    Stephen Marsh
    Community Expert
    Community Expert
    January 18, 2021
    //community.adobe.com/t5/photoshop/looking-for-photoshop-script-that-gives-a-file-a-unique-name-saves-and-close/td-p/10998808
    if (app.documents.length) {
        try { var f = app.activeDocument.fullName } catch (e) {
            var p = new Folder; f = p.selectDlg(); if (f) f = File(f + '/' + app.activeDocument.name)
        }
    
        if (f) {
            activeDocument.saveAs(createUniqueFileName(f))
            activeDocument.close()
        }
    }
    
    function createUniqueFileName(f) {
        var inPath = decodeURI(f.parent),
            inFile = decodeURI(f.name).replace(/\.[^\.]+$/, '').replace(/_\d+$/,''),
            inExt = '.psd',
            uniqueFileName = File(inPath + '/' + inFile + inExt),
            fileNumber = 1
    
        while (uniqueFileName.exists) {
            uniqueFileName = File(inPath + '/' + inFile + "_" + ('000' + fileNumber).slice(-3) + inExt)
            fileNumber++;
        }
        return uniqueFileName
    }
    Stephen Marsh
    Community Expert
    Community Expert
    January 18, 2021
    #target photoshop
    
    main();
    
    function main() {
        if (!documents.length) return;
        var Name = app.activeDocument.name.replace(/\.[^\.]+$/, '');
        try {
            var savePath = activeDocument.path;
        } catch (e) {
            alert("You must save this document first!");
        }
        var fileList = savePath.getFiles("*.jpg").sort().reverse();
        var Suffix = 0;
        if (fileList.length) {
            Suffix = Number(fileList[0].name.replace(/\.[^\.]+$/, '').match(/\d+$/));
        }
        Suffix = zeroPad(Suffix + 1, 3);
        //var saveFile = File(savePath + "/" + Name + "_" + Suffix + ".jpg");
        var saveFile = File(savePath + "/" + Suffix + ".jpg");
        SaveJPEG(saveFile, 8); // JPEG compression level
    }
    
    function SaveJPEG(saveFile, jpegQuality) {
        jpgSaveOptions = new JPEGSaveOptions();
        jpgSaveOptions.embedColorProfile = true;
        jpgSaveOptions.formatOptions = FormatOptions.STANDARDBASELINE;
        jpgSaveOptions.matte = MatteType.NONE;
        jpgSaveOptions.quality = jpegQuality;
        activeDocument.saveAs(saveFile, jpgSaveOptions, true, Extension.LOWERCASE);
    }
    
    function zeroPad(n, s) {
        n = n.toString();
        while (n.length < s) n = '0' + n;
        return n;
    }
    Participating Frequently
    January 18, 2021

    Yes it is one of those that I tried yesterday.

    I copied your whole script in your last post and tried, here how it went:

     

    I opened my first image, resized it and ran the script you posted

    It saved it as jpeg as 001, good

    Then I pressed Del, to remove the image from Photoshop and dragged the next image, I resized it and ran the script again

    It saved it as jpeg as 001 and so it unfortunately replaced the first newly created image

     

    Somehow it does not detect "001", I think

    Stephen Marsh
    Community Expert
    Community Expert
    January 18, 2021
    Stephen Marsh
    Community Expert
    Community Expert
    January 18, 2021
    // Stephen_A_Marsh
    // 05-01-2021
    // Additional options & menu add
    // Rombout Versluijs
    // 14-01-2021
    
    // Usage 
    // - Because its being added to menu it can be hotkeyed
    // - useFileName > true adds filename as a prefix
    // - jpegQuality > sets save quality . range 1-12
    // - formatOption > 1 Progressive
    //                  2 Optimized Baseline
    //                  3 Standard Baseline
    
    /*
    @@@BUILDINFO@@@ Quick Export as JPG Incremental.jsx 0.0.0.6
    */
    /*
    // BEGIN__HARVEST_EXCEPTION_ZSTRING
    /*
    <javascriptresource>
    <name>$$$/JavaScripts/QuickExportAsJPGIncremental/Menu=Quick Export as JPG Incremental...</name>
     <category>scriptexport</category>
    <menu>export</menu>
    <enableinfo>true</enableinfo>
    </javascriptresource>
    
    // END__HARVEST_EXCEPTION_ZSTRING
    
    */
    // alert(documents.length)
    
    #target photoshop
    
    var useFileName = false; // true - false
    var jpegQuality = 10; // 1-12
    var formatOption = 1; // 1-3         
    
    /* Start Open/Saved Document Error Check - Part A: Try */
    savedDoc();
    
    function savedDoc() {
        // try {
            app.activeDocument.path;
            /* Finish Open/Saved Document Error Check - Part A: Try */
    
            /* Main Code Start */
            // https://forums.adobe.com/message/4453915#4453915
            main();
    
            function main() {
                if (!documents.length) return;
                var Name = app.activeDocument.name.replace(/\.[^\.]+$/, '');
                var savePath = activeDocument.path;
                var fileList = [];
                if(useFileName){
                    var fileList = savePath.getFiles(Name + "*.jpg").sort().reverse();
                } else {
                    var fileList = savePath.getFiles("*.jpg").sort().reverse();
                    var filtered = [];
                    for( i in fileList){
                        var name = String(fileList[i]).split("/").pop(); // Get filename
                        name = name.slice(0,name.length-4); // Split extension from name
                        // alert(name+" "+!isNaN(name))
                        // https://stackoverflow.com/questions/651563/getting-the-last-element-of-a-split-string-array
                        if(!isNaN(name)) filtered.push(name); // Check if name is a number or not > fullname needs to be numbers
                    }
                }
                var Suffix = 0;
                if (fileList.length) {
                    if(useFileName){
                        Suffix = fileList[0].name.replace(/\.[^\.]+$/, '').match(/\d+$/); // Fix for mix of characters & numbers
                        Suffix = Number(String(Suffix).slice(String(Suffix).length-1,String(Suffix).length)); // Fix for Windows
    
                        // alert((fileList[0].name).slice(25,26))
                        // alert((fileList[0].name.replace(/\.[^\.]+$/, '').match(/\d+$/)).slice(fileList[0].name.length-5,fileList[0].name.length-4))
                        // alert((fileList[0].name.replace(/\.[^\.]+$/, '').match(/\d+$/)).slice(fileList[0].name.length-1,fileList[0].name.length))
                        // alert((fileList[0].name).slice(fileList[0].name.length-1,fileList[0].name.length))
                        // Suffix = Number(fileList[0].name.replace(/\.[^\.]+$/, '').match(/\d+$/)); // strips numbers when mixed
                        // Suffix = Number(fileList[0].name.match(/\d+$/)); // return true name even when mixed numbers and characters
                    } else if ((!filtered[0] === undefined) || filtered[0]) {
                        Suffix = Number(filtered[0].replace(/\.[^\.]+$/, '').match(/\d+$/));
                    }
                }
                Suffix = zeroPad(Suffix + 1, 3);
                Name = useFileName ? (Name +"_") : "";
                var saveFile = File(savePath + "/" + Name + Suffix + ".jpg");
                SaveJPEG(saveFile, jpegQuality, formatOption);
            }
    
            function SaveJPEG(saveFile, jpegQuality, formatOption) {
                jpgSaveOptions = new JPEGSaveOptions();
                jpgSaveOptions.embedColorProfile = true;
                if (formatOption === 1) {
                    jpgSaveOptions.formatOptions = FormatOptions.PROGRESSIVE;
                    jpgSaveOptions.scans = 3;
                } else if (formatOption === 2) {
                    jpgSaveOptions.formatOptions = FormatOptions.OPTIMIZEDBASELINE;
                } else {
                    jpgSaveOptions.formatOptions = FormatOptions.STANDARDBASELINE;
                }
                jpgSaveOptions.matte = MatteType.NONE;
                jpgSaveOptions.quality = Number(jpegQuality);
                activeDocument.saveAs(saveFile, jpgSaveOptions, true, Extension.LOWERCASE);
            }
    
            function zeroPad(n, s) {
                n = n.toString();
                while (n.length < s) n = '0' + n;
                return n;
            }
            /* Main Code Finish */
        // }
    
        /* Start Open/Saved Document Error Check - Part B: Catch */
        // catch (err) {
        //     alert(err)
        //     // alert("An image must be open and saved before running this script!");
        // }
    }
    /* Finish Open/Saved Document Error Check - Part B: Catch */
    Stephen Marsh
    Community Expert
    Community Expert
    January 18, 2021

    OK, I am just going to dump out all of the scripts that I have collected for making sequential/incremented saves. Let's just concentrate on finding one that works for you at a basic level. Perhaps they can then be modified further to do more.

     

    Please post a threaded reply/comment against the script post, then it is obvious which one is being discussed.

     

    Info on saving and installing scripts here:

     

    Downloading and Installing Adobe Scripts

     

    c.pfaffenbichler
    Community Expert
    Community Expert
    April 22, 2017

    Are you talking about a Script (JS, VB or AS) or an Action?

    In any case you may want to post over at

    Photoshop Scripting

    matt.cortright@gmail.com
    Participant
    April 22, 2017

    sorry, i mean a photoshop action.  that was confusing of me.

    c.pfaffenbichler
    Community Expert
    c.pfaffenbichlerCommunity ExpertCorrect answer
    Community Expert
    April 22, 2017

    Check out this thread: Progressive Save As New Jpeg