9 Replies Latest reply on Jun 26, 2009 9:17 AM by Kasyan Servetsky

    JS CS3 Relink image to new path

    John.Kordas Level 1

      I've put a script together that resizes images in a doc. What I've been able to do is rename the resized image  and then relink to the renamed images. I'd like to be able to have all the resized images saved into the folder using the doc name which is not hard. What I am finding difficult is setting the path to that folder for the relink.

       

      for example:

       

      var myLinks = app.activeDocument.allGraphics;
      var myFpath = myLinks[0].itemLink.filePath
      var myFname = myLinks[0].itemLink.name

       

      $.write(myFpath.replace(myFname,app.activeDocument.name+"/"+myFname) +"\r");

       

      returns C:\hold\Untitled-1/file_24791_Scaled.tif

       

      if I try and change +"/"+ to +"\"+ the remaining code is commented out I've also tried "/\/" which returned //

       

      should I try using replace to return /C/hold/Untitled-1/file_24791_Scaled.tif which should work on both PC and Mac?

       

      Any suggestions would be appreciated.

       

      Cheers, John.

        • 1. Re: JS CS3 Relink image to new path
          Kasyan Servetsky Level 5

          It's not totally tested -- don't have a Mac right now, but I would use the following approach:

           

          var myGraphics = app.activeDocument.allGraphics;
          var aLink = myGraphics[0].itemLink;
          var myFname = aLink.name
          var myFpath = aLink.filePath;
          var aFile = new File(myFpath);
          var aFolder = aFile.parent;
          var aFolderPath = aFolder.absoluteURI;
          if (File.fs == "Windows") {
              var aNewFolder = aFolderPath + "/" + app.activeDocument.name.match(/(.*)\.[^\.]+$/)[1] +  "/" + myFname;
          }
          else if (File.fs == "Macintosh") {
              var aNewFolder = aFolderPath + ":" + app.activeDocument.name.match(/(.*)\.[^\.]+$/)[1] +  ":" + myFname;
          }
          alert(aNewFolder);

           

          Hope this helps.

           

          Kasyan

          • 2. Re: JS CS3 Relink image to new path
            John.Kordas Level 1

            Thanks Kasyan that did the job.

             

            I did have to make a slight change for the Mac process. My script works on resizing tif files so for the PC path I had to use .tif and for the Mac I used .tiff.

             

            I also found that the ":" did not work but "/"did.

             

             

            if (File.fs == "Windows") {
                var aNewFolder = aFolderPath + "/" + app.activeDocument.name.match(/(.*)\.[^\.]+$/)[1] +  "/" + myFname+"_Scaled.tif";
                }
                else if (File.fs == "Macintosh") {
                    var aNewFolder = aFolderPath + "/" + app.activeDocument.name.match(/(.*)\.[^\.]+$/)[1] +  "/" + myFname+"_Scaled.tiff";
                }

             

            Much appreciated for your help.

            • 3. Re: JS CS3 Relink image to new path
              Kasyan Servetsky Level 5

              I've written a script that resizes images images too:

              http://kasyan.ho.com.ua/resize.html

              Check it out, if you are interested.

               

              Kasyan

              • 4. Re: JS CS3 Relink image to new path
                John.Kordas Level 1

                Thanks Kasyan,

                 

                I've had a look at your site and there are some fantastic examples there. My very little resizing script (compared to your version) simply opens all tif files less than 99% in the ID doc and does a resize, unsharp mask and saveAs to a folder named the ID doc name and adds _Scaled tp the end of the file name.

                 

                One thing I noticed in your script that I was not sure about where these 2 lines:

                 

                bt.onResult = function(resObj) {} // empty function - to wait until PS finishes processing the file

                I found an example on the forum that passed commands to PS and it did not have this in it and the first tests I've done with my script have worked ok. If you did not have this in the code what would happen?

                 


                bt.send(100); // !!! bt.send(1);

                Again the example I found did not have 100 so not sure why you use this.

                 

                 

                One issue I have come across is if the person creating the doc uses an image and duplicates it several time and also resizes the frame each time this could cause and issue as there is only one image.  I've been trying to think of a way to loop through the links and flag duplicates and version the links. Have you tried something like this before?

                 

                Cheers John.

                • 5. Re: JS CS3 Relink image to new path
                  Kasyan Servetsky Level 5

                   

                  bt.onResult = function(resObj) {} // empty function - to wait until PS finishes processing the file

                  This function makes ID script to wait until PS finishes execution of the script send by BridgeTalk message. Without it ID just sends BT message and continues executing the 'main' script while Photoshop hasn't resized, saved and closed an image yet, which leads to an error.

                   

                   

                  bt.send(100); // !!! bt.send(1);

                  This is an optional parameter – timoutInSecs.

                  A maximum number of seconds to wait for a result before returning from this function. The message is sent synchronously, and the function does not return until the target has processed the message or this number of seconds have passed. If not supplied or 0, the message is sent asynchronously, and the function returns immediately without waiting for a result.

                   

                  I don't remember why I chose exactly 100, it was so long ago. The odds are that I saw it in some example on the forum.

                   

                  I've been trying to think of a way to loop through the links and flag duplicates and version the links. Have you tried something like this before

                   

                  I've solved this in my script: it finds the largest image (see findLargestLink function) and resizes it, all other images are scaled by ID, while updated – Preferences > File Handling > Relink Preserves Dimensions should be checked (and they are checked by default).

                   

                  Kasyan

                  • 6. Re: JS CS3 Relink image to new path
                    John.Kordas Level 1

                    Here is the PS part of the script which I must admit has only been run on a handful of jobs but one of the main ones is a job with 14 images that need to be resized. The script just seems to opening each image resizing/unsharpen/saveAs/revert/close with no errors. That is so far.  With the findLargestLink() the issue is that all images should be set to 100% otherwise any enhancements made are lost. Would it be possible to version all the duplicates?

                     

                     

                    Call PS function:

                    
                    

                    var myLinks = app.activeDocument.allGraphics;
                    for ( var i = myLinks.length-1; i >= 0; i-- ){ 
                        if(myLinks[i].itemLink.parent.absoluteHorizontalScale < 99 && myLinks[i].itemLink.linkType == 'TIFF'){
                             ResizeInPS( myLinks[i].itemLink.filePath, myLinks[i].itemLink.parent.absoluteHorizontalScale, myLinks[i].itemLink.parent.absoluteVerticalScale, theResolution, theResampleMethod, app.activeDocument.name.split (".")[0] ); 
                            }
                        if(i == 0){
                            LastImage(myLinks[i].itemLink.filePath)
                            }
                    }
                    while (myLinks[0].itemLink.status == LinkStatus.NORMAL )
                    {
                    // think about the weather
                    }

                     

                     

                     

                    PS function.

                     

                    
                    

                    function ResizeInPS(myPath, myHorScale, myVerScale, myResolution, myResampleMethod, myNewFolder) {  
                       var bt = new BridgeTalk;  
                       bt.target = "photoshop";  
                       var myScript = 'try {\n';  
                       myScript += 'var myPsDoc = app.open(File(\"' + myPath + '\"));\n';  
                       myScript += 'app.preferences.rulerUnits = Units.PERCENT; \n' ;  
                       myScript += 'myPsDoc.resizeImage(' +  Math.round(myHorScale) +', ' +  Math.round(myVerScale) + ',myPsDoc.resolution, ' + myResampleMethod + '); \n' ;
                       myScript += 'myPsDoc.artLayers[0].applyUnSharpMask(132,1.5,2); \n' ;

                     

                       myScript += 'var myNewFolder = new Folder(myPsDoc.path+"/'+myNewFolder+'/"); \n' ;
                       myScript += 'if (myNewFolder.exists){ \n' ;
                       myScript += '}else{ \n' ;
                       myScript += 'myNewFolder.create(); \n' ;
                       myScript += '} \n' ;

                     

                       myScript += 'var justname = myPsDoc.name.split ("."); \n' ;
                       myScript += 'newFile = new File( myNewFolder+"/"+justname[0]+"_Scaled.tiff" ); \n' ;
                       myScript += 'tiffSaveOptions = new TiffSaveOptions(); \n' ;
                       myScript += 'tiffSaveOptions.embedColorProfile = false; \n' ;
                       myScript += 'tiffSaveOptions.jepgQuality =10; \n' ;
                       myScript += 'tiffSaveOptions.matte = MatteType.NONE; \n' ;
                       myScript += 'myPsDoc.saveAs(newFile, tiffSaveOptions, true,Extension.LOWERCASE); \n' ;
                    myScript += 'revert( myPsDoc );'; 
                       //myScript += 'myPsDoc.close(SaveOptions.SAVECHANGES);\n';
                       myScript += 'myPsDoc.close(SaveOptions.SAVECHANGES);\n'; 
                       myScript += '}\n';  
                       myScript += 'catch (myError) {\n';  
                       myScript += 'myPsError += \"myError' + myPath + '\";\n';  
                       myScript += '}';  
                      
                       myScript += 'function revert(doc){';  
                       myScript += 'var desc = new ActionDescriptor();';  
                       myScript += ' var ref = new ActionReference();';  
                       myScript += ' ref.putName( charIDToTypeID( "SnpS" ), doc.name );';  
                       myScript += 'desc.putReference( charIDToTypeID( "null" ), ref );';  
                       myScript += 'executeAction( charIDToTypeID( "slct" ), desc, DialogModes.NO );';  
                       myScript += '};'; 
                       bt.body = myScript;  
                       bt.send();  
                    }

                    • 7. Re: JS CS3 Relink image to new path
                      Kasyan Servetsky Level 5

                      In my script, I ‘collect’ all images before resizing them in CollectImages function, which calls another function – LinkUsage to find out how many times the link was placed – and adds the link either to myLinks array (if placed once) or to myMultiUsedLinks array (if placed more then once).

                      You can use the same approach: if a link has duplicates, save each instance as a copy and add a suffix e.g. SomeFile_Scaled_1.tiff, SomeFile_Scaled_2.tiff and so on.

                       

                      Kasyan

                      1 person found this helpful
                      • 8. Re: JS CS3 Relink image to new path
                        John.Kordas Level 1

                        Thanks to Kasyan's LinkUsage function I was able to put this script together.

                         

                        The script is set to look for Tiff and PSD files that are scaled at less then 99%. It will rename the file a version and update the indesign document with that version.

                         

                        So if you have a doc with Ducky.tif duplicated 3 times in the link panel you will see 3 instances of Ducky.tif. After running the script you will find that in the folder that holds the indd doc a folder named the same as the indd doc is created and within it will be Ducky_3.tif and Ducky_2.tiff. The script will also relink to these new versions of the file.

                         

                        This script could be changes to allow other types of files but for some reason I've found that if I open a JPG using the PhotoShop script the save dialog opens in Photoshop require user to ok it. I do not seem to get the same issues with Tiff and PSD files. If there is something I'm doing wrong please let me know.

                         

                        
                        

                        var myDocName = app.activeDocument.name.split(".")[0];
                        var myDocPath = app.activeDocument.filePath+"/"+app.activeDocument.name.split (".")[0]+"/";

                         


                        var myLinks = app.activeDocument.allGraphics;

                         

                        for ( var r = myLinks.length-1; r >= 0; r-- ){ 
                            if(myLinks[r].itemLink.parent.absoluteHorizontalScale < 99 && (myLinks[r].itemLink.linkType == 'TIFF' || myLinks[r].itemLink.linkType == 'Photoshop')){

                         

                        if(LinkUsage(myLinks[r].itemLink)>1){
                        var verFName = myLinks[r].itemLink.name.split (".")[0];   
                        var verNum = LinkUsage(myLinks[r].itemLink)

                         

                        VersionInPS( myLinks[r].itemLink.filePath, myDocPath, verNum);
                                   
                                    if (File.fs == "Windows") {
                            var aVerFolder = myDocPath + verFName +"_"+verNum+".tif";
                            }
                            else if (File.fs == "Macintosh") {
                                var aVerFolder = myDocPath  + verFName+"_"+verNum+".tiff";
                            }               
                                    myLinks[r].itemLink.relink( File(aVerFolder));
                                }
                            }
                        }

                         

                        for ( var u = myLinks.length-1; u >= 0; u-- ){ 
                            myLinks[u].itemLink.update();
                            }

                         

                        function VersionInPS(myPath, myDocPath, myVersion) { 

                         

                           var bt = new BridgeTalk;  
                           bt.target = "photoshop";  
                           var myScript = 'try {\n';  
                           myScript += 'var myPsDoc = app.open(File(\"' + myPath + '\"));\n';  
                          
                           myScript += 'var myNewFolder = new Folder("'+myDocPath+'"); \n' ;
                           myScript += 'if (myNewFolder.exists){ \n' ;
                           myScript += '}else{ \n' ;
                           myScript += 'myNewFolder.create(); \n' ;
                           myScript += '} \n' ;

                         

                           myScript += 'var justname = myPsDoc.name.split (".")[0]; \n' ;
                           myScript += 'newFile = new File( myNewFolder+"/"+justname+"_"+'+myVersion+' ); \n' ;
                           myScript += 'tiffSaveOptions = new TiffSaveOptions(); \n' ;
                           myScript += 'tiffSaveOptions.embedColorProfile = false; \n' ;
                           myScript += 'tiffSaveOptions.jepgQuality =10; \n' ;
                           myScript += 'tiffSaveOptions.matte = MatteType.NONE; \n' ;
                           myScript += 'myPsDoc.saveAs(newFile, tiffSaveOptions, true,Extension.LOWERCASE); \n' ;
                           myScript += 'myPsDoc.close(SaveOptions.DONOTSAVECHANGES);\n'; 
                           myScript += '}\n';  
                           myScript += 'catch (myError) {\n';  
                           myScript += 'myPsError += \"myError' + myPath + '\";\n';  
                           myScript += '}';  
                             
                           bt.body = myScript;
                           bt.onResult = function(resObj) {} // empty function - to wait untill PS finishes processing the file
                           bt.send(100); // !!! bt.send(1);
                        }

                         

                        function LinkUsage(myLink) {
                            var myLinkCounter = 0;
                                for (var myCounter =  0; myCounter < myLinks.length; myCounter++) {
                                if (myLink.filePath == myLinks[myCounter].itemLink.filePath) {
                                    myLinkCounter++;
                                }
                            }
                            return myLinkCounter
                        }

                        • 9. Re: JS CS3 Relink image to new path
                          Kasyan Servetsky Level 5

                          ...I've found that if I open a JPG using the PhotoShop script the save dialog opens in Photoshop require user to ok it. ...

                          If there is something I'm doing wrong please let me know.

                           

                          In my script I temporarily turn off dialogs in Photoshop:

                          SetDisplayDialogs("NO"); // turn OFF on start

                          ...

                          SetDisplayDialogs("ALL"); // turn ON at the end

                           

                          function SetDisplayDialogs(Mode) {
                              var bt = new BridgeTalk;
                              bt.target = "photoshop";
                              var myScript = 'app.displayDialogs = DialogModes.' + Mode + ';';
                              bt.body = myScript;
                              bt.send();
                          }

                           

                          But there is one issue I want to draw your attention to: when you open, resize and save a jpeg file, PS saves it at medium quality 5 by default. For prepress it's a good idea to set quality to maximum - 12.