Skip to main content
micheled87465710
Participant
March 29, 2016
Question

I need to set the maximum compression that does not exceed 370KB.

  • March 29, 2016
  • 1 reply
  • 573 views

Hello, all.

I'm a novice when it comes to scripts in Photoshop, but I'm really coming to the conclusion that this is the only way to automate the actions I need to do, whithout having to do it one-by-one.

Is it possible to write a Script to automatically choose the option (and settings) to "Optimize to file size" in the "Save for Web" dialog?

Is it also possible to save the file in the document's original folder?

I only have a restriction of size (370Kb) for thosefiles, and I would like to save all of them, in each document original folder, with the best possible quality within that size constraint.


I Have this script, but have any problem, do not save in the same folder:



// MAC Finder ou WINDOWS Explorer, on autorise le double clic  et on fait passer Photoshop au 1er plan  

#target photoshop 

app.bringToFront(); 

 

// We shall have to work in pixels 

var regleUnite = app.preferences.rulerUnits; 

app.preferences.rulerUnits = Units.PIXELS; 

 

// Variables declaration 

var sizeMax = 360; // Kb 

sizeMax *=1024; // Conversion to bytes  

var fileName = new File(); 

var qlt = 100; // Quality 

var sizeImg=1000000; // We choose a great value 

         

var docRef = activeDocument; 

 

var docName  = docRef.name; 

var docName  = docName.substring( 0, docName.indexOf('.') );  

var imgWidth = docRef.width; 

var imgHeight = docRef.height; 

 

// The image is resized 

docRef.resizeImage(imgWidth, imgHeight); 

 

var exportOptionsSaveForWeb = new ExportOptionsSaveForWeb(); 

exportOptionsSaveForWeb.format = SaveDocumentType.JPEG; 

exportOptionsSaveForWeb.includeProfile = true; 

 

while (sizeImg > sizeMax) 

    fileName = new File(docRef.path + docName+qlt+".jpg"); 

    exportOptionsSaveForWeb.quality = qlt; 

    docRef.exportDocument (fileName, ExportType.SAVEFORWEB, exportOptionsSaveForWeb);

    qlt-=1; 

    sizeImg = fileName.length; 

    if (sizeImg>sizeMax) 

    { 

        fileName.remove();         

    } 

This topic has been closed for replies.

1 reply

MR74270
Inspiring
March 29, 2016

// Enables double clicking from the Macintosh Finder or Windows Explorer 

#target photoshop

app.bringToFront();

// We shall work in pixels

var rulerPreference = app.preferences.rulerUnits;

app.preferences.rulerUnits = Units.PIXELS;

// The user chooses the largest dimension and the maximum size for his Web image

var maxDimension = prompt("Which is (in pixels) the largest dimension\n (height or width) that you need ?", "");

var maxSize = prompt("Which is (in Kb) the maximum\n size of the optimized file ?", "");

maxSize *=1024; // Kb to Bytes

var inputFolder = Folder.selectDialog("Select the folder where your image is : ");

var selectedFile = inputFolder.openDlg("Select the image to optimize : " , "Select:*.jpg");

var docRef = app.open (selectedFile);

var imgWidth = docRef.width;

var imgHeight = docRef.height;

// Portrait or Landscape ?

if (imgWidth<imgHeight)

{

    imgWidth = Math.round(maxDimension * imgWidth / imgHeight);

}

else

{

    imgWidth = maxDimension;

}

var outputFolder = Folder(docRef.path+'/');

var nameSaveRef = new File( outputFolder + '/_' + docRef.name); 

var newFileRef = new File( nameSaveRef );

// maximum initial % quality

var qlty = 100; 

 

// resize the image to the right width 

docRef.resizeImage(UnitValue(imgWidth,"px"),null,100,ResampleMethod.BICUBICSHARPER); 

 

// Perform the first SaveForWeb Operation

alert("Click on \"OK\" and wait about 15 seconds. You will receive another message when your image will be ready.") 

ExportWeb(newFileRef, qlty); 

 

// Keep trying to save the file with maximum quality under maxSize     

while (newFileRef.length > maxSize) 

    qlty -= 1; 

    newFileRef = new File( newFileRef );    

    newFileRef.remove(); 

    ExportWeb(newFileRef, qlty);  // Perform a new SaveForWeb Operation, with slightly lower qlty 

}

 

// close the original file without saving 

activeDocument.close(SaveOptions.DONOTSAVECHANGES);

open(newFileRef);

alert("Your image is ready. The best quality rate is " + qlty + " %");

// Restore user's preference

app.preferences.rulerUnits=rulerPreference; 

 

// SaveForWeb Export, with the desired constraints and parameters 

function ExportWeb(file, qlty) 

      var options = new ExportOptionsSaveForWeb(); 

      options.quality = qlty;   // Start with highest quality (biggest file). 

      options.format = SaveDocumentType.JPEG;   // Save Format for the file 

      docRef.exportDocument(File(file), ExportType.SAVEFORWEB, options); 

}

When I wrote this code, somebody asked me to limit not only the size of the optimized picture, but the largest dimention also. This is the new code :

!

micheled87465710
Participant
March 30, 2016

ok. Thank you.

but I need a script to be included in action.

without the possibility to choose the folder.

Thank you so much

MR74270
Inspiring
April 1, 2016

Bonjour

Add + "/" 107 line like this:
fileName = new File + (docRef.path + "/" +  docName qlt + "jpg.");


I had a problem when there was spaces in fileNames. In the following example, a recursive function puts in an array the pictures found in a top folder and its subFolders and optimize them for the Web.

Line 12 you can change the maximum dimension of your pictures (in pixels) and line 13 its maximum size. Optimized files are saved in the original folders and begin with an underscore.

You can try this.hopping it will help. Sorry for the previous bug.

// Enables double clicking from the Macintosh Finder or Windows Explorer

#target docRefshop

app.bringToFront();

// We shall work in pixels

var rulerPreference = app.preferences.rulerUnits;

app.preferences.rulerUnits = Units.PIXELS;

alert("After launching this script, you must wait the message that will inform you that the execution is finished");

// The user chooses here the largest dimension and the maximum size for his Web image

var maxDimension=900; // in pixels

var maxSize = 370; // in KBytes

maxSize *=1024; // Conversion to bytes

var inputFolder = Folder.selectDialog("Select the top folder where your images are : ");

if (inputFolder != null) {

    filesArray = scanFolder(inputFolder);

    if (filesArray.length > 0)

    {

        for (i = 0;i<filesArray.length;i++)

        {

            var docRef = filesArray;

            var inputFolder=docRef.path+"/";

            var docName = "_"+docRef.name;

            app.open (docRef);

            // Portrait or Landscape ?

            var imgWidth = app.activeDocument.width;

            var imgHeight = app.activeDocument.height;

            if (imgWidth<=imgHeight) // Portrait

            {

                imgWidth = Math.round(maxDimension * imgWidth / imgHeight);

                alert("image verticale");

            }

            else // Landscape

            {

                imgWidth = maxDimension;

            }           

            // Resizes the image in the maximum dimension and optimize it 

            app.activeDocument.resizeImage(UnitValue(imgWidth,"px"),null,100,ResampleMethod.BICUBICSHARPER); 

            optimization();

        }

    }

}

// Recursive function

function scanFolder(folder) {

    var filesArray = [],

    fileList = folder.getFiles(),i, file;

   

    for (i = 0; i < fileList.length; i++) {

        file = fileList;

        if (file instanceof Folder) {

            filesArray = filesArray.concat(scanFolder(file));

        }

        else if (file instanceof File && file.name.match(/\.(jpg|tif|psd|bmp|gif|png|)$/i)) {

            filesArray.push(file);

        }

    }

    return filesArray;

}

function optimization()

{

    var tempFile = File(inputFolder + '_tmp.jpg');

    var qlty = 100; // Begins with maximum quality

    ExportWeb(tempFile, qlty);    

     

    // Optimization trial with a decreasing step of 10 %     

    while (tempFile.length > maxSize) 

    { 

        qlty -= 10; 

        tempFile = new File(tempFile);    

        tempFile.remove(); 

        ExportWeb(tempFile, qlty);   

    }

    // Optimization trial with a step of 1 %

    if (qlty<100)

    {

        qlty+=10;

        tempFile = new File(tempFile);    

        tempFile.remove(); 

        ExportWeb(tempFile, qlty);   

        while (tempFile.length > maxSize) 

        { 

            qlty -= 1;

            tempFile = new File(tempFile);    

            tempFile.remove();

            ExportWeb(tempFile, qlty);   

        }

    }

    // Closes the original doc, loads the optimized image and saves it 

    activeDocument.close(SaveOptions.DONOTSAVECHANGES);

    var newFile = open(tempFile);

    var saveFile = File(inputFolder+docName);

    ExportWeb(saveFile, qlty);

    activeDocument.close(SaveOptions.DONOTSAVECHANGES);

    // Now the temporary file can be killed

    tempFile.remove();

    // Save function for Web optimization 

    function ExportWeb(fileName, qlty) 

    { 

        var options = new ExportOptionsSaveForWeb(); 

        options.quality = qlty;    

        options.format = SaveDocumentType.JPEG;    

        options.includeProfile = false;

        options.interlaced = false;

        options.optimized = true;     

        app.activeDocument.exportDocument(fileName, ExportType.SAVEFORWEB, options);     

    }

}

// Restore user's preference - End of scripts

app.preferences.rulerUnits=rulerPreference;

alert("Done. Your optimized files begin with an underscore.");