2 Replies Latest reply on Jan 4, 2016 10:15 PM by michelr31372089

    How to use script to optimize picture file size?

    MrDesign

      This is the script that I am looking for from the Internet, although feasible, very slow.

      // save jpg;  
      // 2015, use it at your own risk;  
      #target photoshop
      
      
      //Save a fixed width image with a size constraint in its original folder  
      
      
      // quality/size constraints  
      var w = 300; // new file width  
      var MaxSz =  61440; // max. 60Kb  
      var Qlt = 100; // initial quality 100  
      
      
      //
      function GetDataFromDocument( inDocument ) {
        var data = new Object();
        var fullPathStr = inDocument.fullName.toString();
        var lastDot = fullPathStr.lastIndexOf( "." );
        var fileNameNoPath = fullPathStr.substr( 0, lastDot );
        data.extension = fullPathStr.substr( lastDot + 1, fullPathStr.length );
        var lastSlash = fullPathStr.lastIndexOf( "/" );
        data.fileName = fileNameNoPath.substr( lastSlash + 1, fileNameNoPath.length );
        data.folder = fileNameNoPath.substr( 0, lastSlash );
        return data;
      }
      
      
      var docRef = activeDocument;
      var data=GetDataFromDocument(activeDocument);
      var folder=new Folder(data.folder+"/Samples/");//
       fileData=data.folder +  '/'+data.fileName+".jpg";//
        
      
      
      NameSave = new File( fileData);  
      var NewFile = new File( NameSave ) ;
      
      
      // resize the image to the right width  
      //docRef.resizeImage(UnitValue(w,"px"),null,100,ResampleMethod.BICUBICSHARPER);  
        
      // Perform the first SaveForWeb Operation  
      ExpWeb(NewFile, Qlt);  
        
      // Keep trying to save the file with max. Qlt, but under MaxSz      
      while (NewFile.length > MaxSz)  
      {  
            Qlt = Qlt -1;  
            NewFile = new File( NewFile );     
            NewFile.remove();  
            ExpWeb(NewFile, Qlt);  // Perform a new SaveForWeb Operation, with slightly lower Qlt  
               if (Qlt <=50) {  
                 alert("");  
                 break  // break the loop whenever the quality is as low as 50 (this shouldn't need to happen)  
               }  
      }  
        
      var FileSz = NewFile.length/1024;  
      FileSz = Math.round(FileSz);  
        
      // close the original file without saving  
      activeDocument.close(SaveOptions.DONOTSAVECHANGES);  
        
      // SaveForWeb Export, with the desired constraints and parameters  
      function ExpWeb(FileNm, Qlt)  
      {  
            var options = new ExportOptionsSaveForWeb();  
            options.quality = Qlt;   // Start with highest quality (biggest file).  
            options.format = SaveDocumentType.JPEG;   // Save Format for the file  
            docRef.exportDocument(File(FileNm), ExportType.SAVEFORWEB, options);  
      }  
      
        • 1. Re: How to use script to optimize picture file size?
          c.pfaffenbichler Level 9

          You could increase the Quality decrease steps thus cutting down on the number of iterations, though the result may be more off from the target size than otherwise.

           

          But the method simply has the potential to take a long time because the exact compression result is practically unpredictable and thus the individual save steps can hardly be avoided.

          • 2. Re: How to use script to optimize picture file size?
            michelr31372089 Level 2

            On another forum, the maximum size of an image is 300 Kb. Portrait and Landscape sizes are limited to 800 and 600 pixels. To 600 and 600 pixels for a square format.

             

            You can try and adapt the  following code :

             

            // 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 = 300; // Kb
            sizeMax *=1024; // Conversion to bytes 
            var fileName = new File();
            var qlt = 100; // Quality
            var sizeImg=1000000; // We choose a great value
                    
            var inputFolder = Folder.selectDialog("Select the folder of the image : ");
            var outputFolder = Folder(inputFolder + "/save");
            // A save sub-folder is created
            if (!outputFolder.exists) outputFolder.create();
            app.displayDialogs = DialogModes.NO;
            
            var selectedFile = inputFolder.openDlg("Select an image : " , "Select:*.jpg");
            var docRef = open(selectedFile);
            var docName  = docRef.name;
            var docName  = docName.substring( 0, docName.indexOf('.') ); 
            var imgWidth = docRef.width;
            var imgHeight = docRef.height;
            
            // The image size is calculated respecting its ratio
            if (imgWidth>imgHeight) // Landscape
            {
                imgHeight = 800*imgHeight/imgWidth;
                imgWidth = 800;
            }
            else if(imgWidth<imgHeight) // Portrait
            {
                imgWidth = 800*imgWidth/imgHeight;
                imgHeight = 800;    
            }
            else // Square format
            {
                imgWidth = 600;
                imgHeight = 600;
            }
            
            // The image is resized
            docRef.resizeImage(imgWidth, imgHeight);
            
            var exportOptionsSaveForWeb = new ExportOptionsSaveForWeb();
            exportOptionsSaveForWeb.format = SaveDocumentType.JPEG;
            exportOptionsSaveForWeb.includeProfile = true;
            
            alert("Click [OK] and wait some seconds.");
            
            while (sizeImg > sizeMax)
            {
                fileName = File(docRef.path + "/save/" + docName+qlt+".jpg");
                exportOptionsSaveForWeb.quality = qlt;
                docRef.exportDocument (fileName, ExportType.SAVEFORWEB, exportOptionsSaveForWeb);
                qlt-=1;
                sizeImg = fileName.length;
                if (sizeImg>sizeMax)
                {
                    fileName.remove();        
                }
            }
            
            // Restauration of the user's preference
            app.preferences.rulerUnits = regleUnite;
            app.activeDocument.close(SaveOptions.DONOTSAVECHANGES);
            qlt+=1;
            alert("Done. The image has been saved in the sub-folder ../save/ with an optimized quality of "+qlt+ " %");