10 Replies Latest reply: Nov 24, 2011 5:07 PM by Photropik RSS

    Need script to batch import images into PSD layer

    obeacon

      Hi,

      I have a large group of identically sized Illustrator PDF images (I could convert these to jpeg and resize separately...). I need to import each of these into a specific part of another image, which will always be constant  The incoming image should be the back layer and the file should be saved as a jpeg, and named after the incoming image's file name. 

      What's the best approach here?

      Thanks, everybody. 

        • 1. Re: Need script to batch import images into PSD layer
          c.pfaffenbichler Community Member

          Do all the pdfs have one page or are they multi-paged ones, too?

          Could you post screenshots of the receiving File’s Layer-structure and what you want the result to be?

          Are the layered files to be saved, too, or discarded and only the jpgs saved?

          Where should the jpg reide relative to the receiving file?

          • 2. Re: Need script to batch import images into PSD layer
            obeacon Community Member

            Each PDF is a single image and all are identical in size, which should make any actions easy.  I'm attaching a screenshot of the photo image I've prepared, which should be a mask for the incoming PDF image. 

            I've also attached a screenshot of one of the incoming images, as seen in illustrator.  (There are a few hundred of these, all subway signs, all the same size.  And artboards match image.)

            Each one needs to be imported and skewed slightly to match the perspective in the photo.  I could do that separately as an action, but I want to make sure it's easy to import all the resulting images correctly into the photo.  Alignment is key.  Can do these nicely one at a time, but obvs that will take forever. 

            Last, the resulting image should become a jpeg with a file name that corresponds to that of the PDF image, not the photo image. 

            Thanks!

            Screen shot 2011-09-27 at 3.26.11 AM.png

            Screen shot 2011-09-27 at 3.24.22 AM.png

            • 3. Re: Need script to batch import images into PSD layer
              c.pfaffenbichler Community Member

              With »skew« do you really mean Skew or Free Transform/Perspective?

               

              Either way I would recommend creating a template file with the Illustrator-file placed as a Smart Object (in case of Free Transform a Smart Object in a Smart Object).

              Then use File.openDialog to select the files and have a for-clause work through the lot, replacing the SO’s content and saving off the jpgs.

              • 4. Re: Need script to batch import images into PSD layer
                c.pfaffenbichler Community Member

                This should work along the lines I mentioned above.

                If the Smart Object is selected you are presented with a file selection dialog, the selected files are then switched in for the SO and jpgs are saved next to the container-file.

                In case of a SO inside a SO another step (opening the SO, replacing contents, saving and closing SO) would have to be included.

                 

                // replace smart object’s content and save jpg;
                // 2011, use it at your own risk;
                #target photoshop
                if (app.documents.length > 0) {
                var myDocument = app.activeDocument;
                var thePath = myDocument.path;
                var theLayer = myDocument.activeLayer;
                // jpg options 
                var jpgopts = new JPEGSaveOptions();
                jpgopts.embedProfile = true;
                jpgopts.formatOptions = FormatOptions.STANDARDBASELINE;
                jpgopts.matte = MatteType.NONE;
                jpgopts.quality = 10;
                // check if layer is smart object;
                if (theLayer.kind != "LayerKind.SMARTOBJECT") {alert ("selected layer is not a smart object")}
                else {
                // select files;
                if ($.os.search(/windows/i) != -1) {var theFiles = File.openDialog ("please select files", "*.pdf;*.ai", true)} 
                else {var theFiles = File.openDialog ("please select files", getFiles, true)};
                if (theFiles.length > 0) {
                // work through the array;
                          for (var m = 0; m < theFiles.length; m++) {
                // replace smart object;
                                    theLayer = replaceContents (theFiles[m])
                //save jpg;
                                    myDocument.saveAs((new File(thePath+"/"+theFiles[m].name+".jpg")),jpgopts,true);
                                    }
                          }
                }
                };
                ////// get psds, tifs and jpgs from files //////
                function getFiles (theFile) {
                    if (theFile.name.match(/\.(pdf|ai)$/i)) {
                        return true
                        };
                          };
                ////// replace contents //////
                function replaceContents (newFile) {
                // =======================================================
                var idplacedLayerReplaceContents = stringIDToTypeID( "placedLayerReplaceContents" );
                    var desc3 = new ActionDescriptor();
                    var idnull = charIDToTypeID( "null" );
                    desc3.putPath( idnull, new File( newFile ) );
                    var idPgNm = charIDToTypeID( "PgNm" );
                    desc3.putInteger( idPgNm, 1 );
                executeAction( idplacedLayerReplaceContents, desc3, DialogModes.NO );
                return app.activeDocument.activeLayer
                };
                
                • 5. Re: Need script to batch import images into PSD layer
                  obeacon Community Member

                  This is excellent, CP. 

                  I'll give this a try.  Thanks for the support!

                  • 6. Re: Need script to batch import images into PSD layer
                    c.pfaffenbichler Community Member

                    This Script would work if the selected layer is a Smart Object that contains one other Smart Object.

                    I accidentally put the Gradient Overlay in there, too – you could do that in the containing document, though.

                    The screenshot shows the file’s Layers Panel and the Finder window with the pdfs and the resultant jpgs.

                    switchSOTest2Scr.jpg

                     

                    // replace smart object’s content and save jpg;
                    // 2011, use it at your own risk;
                    #target photoshop
                    if (app.documents.length > 0) {
                    var myDocument = app.activeDocument;
                    var thePath = myDocument.path;
                    var theLayer = myDocument.activeLayer;
                    // jpg options 
                    var jpgopts = new JPEGSaveOptions();
                    jpgopts.embedProfile = true;
                    jpgopts.formatOptions = FormatOptions.STANDARDBASELINE;
                    jpgopts.matte = MatteType.NONE;
                    jpgopts.quality = 10;
                    // check if layer is smart object;
                    if (theLayer.kind != "LayerKind.SMARTOBJECT") {alert ("selected layer is not a smart object")}
                    else {
                    // select files;
                    if ($.os.search(/windows/i) != -1) {var theFiles = File.openDialog ("please select files", "*.pdf;*.ai", true)} 
                    else {var theFiles = File.openDialog ("please select files", getFiles, true)};
                    if (theFiles) {
                    // work through the array;
                              for (var m = 0; m < theFiles.length; m++) {
                    // open smart object;
                                        var smartObject = openSmartObject (theLayer);
                                        var theLayer2 = smartObject.activeLayer;
                    // replace smart object;
                                        if (theLayer2.kind == "LayerKind.SMARTOBJECT") {
                                                  replaceContents (theFiles[m])
                                                  };
                    // close;
                                        smartObject.close(SaveOptions.SAVECHANGES);
                    //save jpg;
                                        myDocument.saveAs((new File(thePath+"/"+theFiles[m].name+".jpg")),jpgopts,true);
                                        }
                              }
                    }
                    };
                    ////// get psds, tifs and jpgs from files //////
                    function getFiles (theFile) {
                        if (theFile.name.match(/\.(pdf|ai)$/i)) {
                            return true
                            };
                              };
                    ////// replace contents //////
                    function replaceContents (newFile) {
                    // =======================================================
                    var idplacedLayerReplaceContents = stringIDToTypeID( "placedLayerReplaceContents" );
                        var desc3 = new ActionDescriptor();
                        var idnull = charIDToTypeID( "null" );
                        desc3.putPath( idnull, new File( newFile ) );
                        var idPgNm = charIDToTypeID( "PgNm" );
                        desc3.putInteger( idPgNm, 1 );
                    executeAction( idplacedLayerReplaceContents, desc3, DialogModes.NO );
                    return app.activeDocument.activeLayer
                    };
                    ////// open smart object //////
                    function openSmartObject (theLayer) {
                    if (theLayer.kind == "LayerKind.SMARTOBJECT") {
                    // =======================================================
                    var idplacedLayerEditContents = stringIDToTypeID( "placedLayerEditContents" );
                        var desc2 = new ActionDescriptor();
                    executeAction( idplacedLayerEditContents, desc2, DialogModes.NO );
                    };
                    return app.activeDocument
                    };
                    
                    • 7. Re: Need script to batch import images into PSD layer
                      red_dirt_studio Community Member

                      how would you do this without the prompt. SAY you know the file name and want it hard coded in Then if it does not exist call the prompts?

                       

                      I am working on a batch command that does something similar. It will always pull a pdf with the same name as the PSD into a smart object layer within the file.

                      • 8. Re: Need script to batch import images into PSD layer
                        c.pfaffenbichler Community Member

                        Something like this might work (I have only included the selection for Mac but not the getFiles-function, but you should be able to amend that):

                        var myDocument = app.activeDocument;
                        var thePath = myDocument.path;
                        var theName = myDocument.name;
                        var thePdf = thePath+"/"+theName.slice(0, theName.lastIndexOf("."))+".pdf";
                        if (File(thePdf).exists == true) {
                        var theFiles = [thePdf]
                        }
                        else {
                        var theFiles = File.openDialog ("please select files", getFiles, true)
                        };
                        


                        • 10. Re: Need script to batch import images into PSD layer
                          Photropik Community Member

                          Hello.

                           

                          I've tried to adapt this script I to  update a sprite sheet.

                          The sprite sheet contains 6 smart objects, which where created by importing PSD containing 1 transparent rasterized layer, converting to SmartObjects, then repositioning and scaling.

                          The script has two faults. Either it runs and replaces the images, but moves them about vertically.

                          Or it simply throws an "General Photoshop Error. This method may not be.. etc" error and highlights this line :

                           

                          executeAction( idplacedLayerEditContents, desc2, DialogModes.NO );

                           

                          I'm still getting to grips with the completely bonkers API, looking at what looks like assembly language bubbling up through the "baretail" application.

                          Any tips as to why it's erroring out or coming in in the wrong places vertically (looks OK horizontally) most appreciate.

                          It's the bizarre intermittent error that bugs me most, sometimes it runs and does it wrong, sometimes I just get a bing  noise.

                           

                          Script is here :

                          http://www.charlescrammond.co.uk/downloads/ReplaceContentsOfSmartObjects.jsx

                           

                          Sample PSDs I'm using are  here :

                          http://www.charlescrammond.co.uk/downloads/spritesheet.zip

                           

                          any help much appreciated! meanwhile, I guess back to the UI and manually doing it

                           

                          Charles

                           

                           

                           

                           

                          /// Script to automate replacing contents of smart layers with selected psds
                          /// Sometimes it just about works, and replaces the images fine but moves them down vertically.
                          /// Sometimes it throws an error at :
                          ///  executeAction( idplacedLayerEditContents, desc2, DialogModes.NO );

                          #target photoshop

                          if (app.documents.length > 0)
                          {
                             var myDocument = app.activeDocument;
                             var thePath = myDocument.path;

                             var pngopts = new PNGSaveOptions();
                             pngopts.interlace = false;

                          function swapImages()
                          {
                                // select files;
                                if ($.os.search(/windows/i) != -1)
                                {
                                   var theFiles = File.openDialog ("please select files", "*.psd;*.psb", true)
                                }
                                else
                                {
                                   var theFiles = File.openDialog ("please select files", getFiles, true);
                                };

                                if (theFiles)
                                {
                                   // work through the array;
                                   for (var m = 0; m < theFiles.length; m++)
                                   {
                                      // open smart object; in active document
                                      var getLayerToChange = app.activeDocument.artLayers[m];
                                      app.activeDocument.activeLayer = getLayerToChange;
                                      var smartObject = openSmartObject (getLayerToChange);
                                           
                                      // get a reference to the layer within
                                      var theLayer2 = smartObject.activeLayer;
                                      // replace smart object;
                                      if (theLayer2.kind == "LayerKind.SMARTOBJECT")
                                      {
                                         replaceContents (theFiles[m]);
                                         // This closes the current image source file.
                                         smartObject.close(SaveOptions.SAVECHANGES);  
                                         // not  sure this is needed but what the hell
                                         delete smartObject;
                                      };
                                   //save png;
                                   $.writeln("Saving a PNG");
                                   myDocument.saveAs((new File(thePath+"/"+"spritesheet.png")),pngopts,true);
                                   };     
                                };
                             };
                          };

                          ////// get psds and psb  from files //////
                          function getFiles (theFile)
                          {
                             if (theFile.name.match(/\.(psd|psb)$/i))
                             {
                                return true
                             };
                          };

                          ////// replace contents //////
                          function replaceContents (newFile)
                          {
                             var idplacedLayerReplaceContents = stringIDToTypeID( "placedLayerReplaceContents" );
                             var desc3 = new ActionDescriptor();
                             var idnull = charIDToTypeID( "null" );
                             desc3.putPath( idnull, new File( newFile ) );
                             var idPgNm = charIDToTypeID( "PgNm" );
                             desc3.putInteger( idPgNm, 1 );
                             executeAction( idplacedLayerReplaceContents, desc3, DialogModes.NO );
                             //
                             return app.activeDocument.activeLayer
                          };

                          ////// open smart object //////
                          function openSmartObject (theLayer)
                          {
                             if (theLayer.kind == "LayerKind.SMARTOBJECT")
                             {
                                var idplacedLayerEditContents = stringIDToTypeID( "placedLayerEditContents" );
                                var desc2 = new ActionDescriptor();
                                // why does this line here throw errors sometimes, and sometimes not.
                                executeAction( idplacedLayerEditContents, desc2, DialogModes.NO );

                             };
                             return app.activeDocument
                          };


                          // Call main function
                          swapImages();