Skip to main content
Participating Frequently
May 24, 2021
Answered

.jsx Script that saves edited .jpg to subfolder with the same filename.

  • May 24, 2021
  • 3 replies
  • 2726 views

The goal is, preferably in JavaScript, if not possible, seeing as the process is being carried out on a Windows machine VBS is the acceptable alternative, to automate by means of scripting the process of saving a file to relative path, that is, the subfolder within the folder of the original .jpg.

 

Process example is as follows:

 

Opened/active file name: 42.jpg

Save edited file as: 42.jpg

 

Opened/active file folder: ~\jpg

To folder: ~\jpg\Edited

(Folder location not constant which gets absolute path out of the question.)

 

JPEG Options:

Matte: None

Image Options: Quality: 12

Format Options: Baseline ("Standard")

 

Reason for looking into a scripting solution being that, unlike Photoshop's built in Batch processing tool, as far as currently understood, the operation would have to be able to be carried out at certain point, when required, that is, be activated as an Action by keyboard shortcut, and as far as the awareness of capabilities of the Batch tool goes, while it is able to accomplish the task in question where process is fully automated in which case it is extremely useful, when process has to have interuptions for purposes of editing the image or any other kind of user inputto be made, the only remaining option seems that there is perhaps a requirement for a script.

 

Several attempts were made, some of which included copy/pasting a number of whole code sets, with minor changes being made to it for purposes of adaptation, as well as trying, without avail, to make the script for completing the task by crumpling together various snippets of code from multiple sources, though due to heavy limitations of time slot availability and not high enough level of familiarization with JavaScript and coding alltohether as the case may be, such methods were of no use thereby leaving this, that being directly asking for it the only potentially viable option.

 

Thanks in advance.

This topic has been closed for replies.
Correct answer r-bin

 

var doc = activeDocument;
var subfolder = "Edited"; 

var file = new File(doc.path.fsName + "/"+ subfolder + "/" + doc.name); // extention will be the same

var opt = new JPEGSaveOptions();

opt.embedColorProfile = true;
opt.mate = MatteType.NONE;
opt.quality = 12;
optformatOptions = FormatOptions.STANDARDBASELINE;

if (create_folder(new Folder(doc.path.fsName + "/"+ subfolder)))
    doc.saveAs(file, opt, false);
else
    alert("Cant create folder!");

function create_folder(f)
    {
    try {
        if (f.parent && !f.parent.exists) if (!create_folder(f.parent)) return false;

        return f.create();
        }
    catch(e) { return false; }  
    }  

 

 

upd.

again a typo 🙂

optformatOptions = FormatOptions.STANDARDBASELINE;

no dot

3 replies

Stephen Marsh
Community Expert
Community Expert
May 25, 2021

 

Rather than using save as, this version uses export save for web (I know that you have different criteria). I have commented out the code that converts to sRGB.

 

/* This script saves an export save for web JPEG version of a saved file to a sub-folder next to the original image. Existing files will be overwritten without warning! */

#target photoshop

unSaved();

function unSaved() {
    try {
        var d = app.activeDocument;
        var dPath = d.path;

        // Check open image for saved file path
        dPath;

        // File Naming Code
        var dname = d.name.replace(/\.[^\.]+$/, '');
        var sFold = new Folder(dPath + '/Edited')
        if (!sFold.exists) {
            sFold.create()
        }

        // File Saving Code
        var saveFileJPEG = new File(sFold + '/' + dname + '.jpg');
        SaveForWeb(saveFileJPEG);

        // Undo Convert to sRGB Step
        /*
        select();
        function select() {
            var c2t = function (s) {
                return app.charIDToTypeID(s);
            };
            var s2t = function (s) {
                return app.stringIDToTypeID(s);
            };
            var descriptor = new ActionDescriptor();
            var reference = new ActionReference();
            reference.putEnumerated(c2t("HstS"), s2t("ordinal"), s2t("previous"));
            descriptor.putReference(c2t("null"), reference);
            executeAction(s2t("select"), descriptor, DialogModes.NO);
        }
        */

        // JPEG S4W Options
        function SaveForWeb(saveFileJPEG, jpegQuality) {
            /*
            // Convert to sRGB Step
                var doc = app.activeDocument;
                if (doc.colorProfileName.substring(0, 4) != "sRGB")
                doc.convertProfile("sRGB IEC61966-2.1", Intent.RELATIVECOLORIMETRIC, true, false); // BPC, Dither  
            */
            var sfwOptions = new ExportOptionsSaveForWeb();
            sfwOptions.format = SaveDocumentType.JPEG;
            sfwOptions.includeProfile = true;
            sfwOptions.interlaced = 0;
            sfwOptions.optimized = true;
            sfwOptions.quality = 70;
            activeDocument.exportDocument(saveFileJPEG, ExportType.SAVEFORWEB, sfwOptions);
        }

        alert('JPEG version saved to a new sub-folder next to the original image!');

    } catch (err) {
        alert('An image must be both open and saved before running this script!');
    }
}

 

 

I know you have marked correct answers, this is just another way of doing things as a learning exercise/example.

 

EDIT: I had to remove the overwrite warning from the original post. I'll update the code again when I get it sorted...

R-WyattAuthor
Participating Frequently
May 25, 2021

Well, this is definitely getting more than was bargained for. Didn't get to that point yet, but have nevertheless come across that option in Photoshop, Save for Web that is, and, as the processed material is ultimately intended for such purposes, made a mental note to get back to it upon acquiring more free time. However, this is another scheduled coding task taken care of.

Will be testing this portion of code promptly.

 

Thank You.

r-binCorrect answer
Legend
May 24, 2021

 

var doc = activeDocument;
var subfolder = "Edited"; 

var file = new File(doc.path.fsName + "/"+ subfolder + "/" + doc.name); // extention will be the same

var opt = new JPEGSaveOptions();

opt.embedColorProfile = true;
opt.mate = MatteType.NONE;
opt.quality = 12;
optformatOptions = FormatOptions.STANDARDBASELINE;

if (create_folder(new Folder(doc.path.fsName + "/"+ subfolder)))
    doc.saveAs(file, opt, false);
else
    alert("Cant create folder!");

function create_folder(f)
    {
    try {
        if (f.parent && !f.parent.exists) if (!create_folder(f.parent)) return false;

        return f.create();
        }
    catch(e) { return false; }  
    }  

 

 

upd.

again a typo 🙂

optformatOptions = FormatOptions.STANDARDBASELINE;

no dot

R-WyattAuthor
Participating Frequently
May 24, 2021

Well, thanks for giving it a second look and noticing the mistype. Don't know if personally finding any kind of syntax error in the sample above would have been possible. Still, JavaScript grammar aside, this piece of code, although being more complex of the two offered solutions will also be tested and, provided enough time studied more thoroughly as, given it's higher level of complexity when combined with experience in manually completing the operation it was written to automate a hefty number of times is bound to offer quite a bit of insight in the cogworks of JavaScript.

 

Greatly appreciated.

Kukurykus
Legend
May 25, 2021

I read also all your other posts. You have eloquent and wise-kind level of wordings 😉

Kukurykus
Legend
May 24, 2021
(jpg = new JPEGSaveOptions()).quality = 12; aD = activeDocument
if (!File(edtd = aD.path + '/Edited/').exists) Folder(edtd).create()
aD.saveAs(File(edtd + aD.name), jpg)
R-WyattAuthor
Participating Frequently
May 24, 2021

Short and on point, simple enough to make sense to the untrained eye. Tested and working flawlessly.

 

Much appreciated.