12 Replies Latest reply on Jul 27, 2011 7:03 AM by Michael L Hale

    scripting newbee: How can I import a jpg to my document layer?

    JohnDrach13

      I have a question I was hoping someone could help me with.

      I'm trying to set up a script that will layout a template for some ads that I have to make regularly.

      I am able to create the document and set some text but I will also need to import some jpg, gif, png, and ai files from time to time.

      Can someone show me how I would import a jpg from a local file and place it on the layer I'm working in. The task would be similar to:

      file/place/desktop/myFolder.Any help would be appreciated.

       

      This is what i have so far:

       

      var rulerUnits = preferences.rulerUnits
      Preferences.rulerUnits = Units.PIXELS

       

      //Create a new document at 300x250px
      var newDoc = app.documents.add(300, 250)

       

      //////////////////////////////////////////////////////Layer1
      // Create a new art layer containing text
      var FirstLayer = newDoc.artLayers.add()
      FirstLayer.kind = LayerKind.TEXT

       

      //Set  the contents
      var textItem = FirstLayer .textItem
      textItem.contents = "Hello, World!"

       

      textItem.position = [100, 100]

       

      ///////////////////////////////////////////////////////Layer2

       

      var SecondLayer = newDoc.artLayers.add()
      SecondLayer.kind = LayerKind.NORMAL

       

      ////////I WOULD NEED TO IMPORT IMAGE AND PLACE HERE

       

      imageItem.position = [200, 200]

       

      //Release Refrences
      newDoc = null
      FirstLayer = null
      textItemRef = null

        • 1. Re: scripting newbee: How can I import a jpg to my document layer?
          JJMack Most Valuable Participant

          To me it sounds like you trying to make a template and populate it. You may want to look at my Photoshop "Photo Collage Toolkit" with it all you may need to do is create template files and use the supplied scripts to populate them. The are Interactive scripts and fullu automated scripts.

          Some Photo Collage Toolkit Examples

          Documentation and Examples
          Download

          • 2. Re: scripting newbee: How can I import a jpg to my document layer?
            JohnDrach13 Level 1

            Thanks for the reply, I'll take a look at this as soon as I have another minute to experiment at work and report back.

             

            - John

            • 3. Re: scripting newbee: How can I import a jpg to my document layer?
              Michael L Hale Level 5

              You can use scriptlistener to place an image. The script below with work with pixel images like tif, jpg, etc. For ai or eps you will need a different scriptlistener function or modify the one supplied.

               

              var rulerUnits = preferences.rulerUnits
              Preferences.rulerUnits = Units.PIXELS
              
              //Create a new document at 300x250px
              var newDoc = app.documents.add(300, 250)
              
              //////////////////////////////////////////////////////Layer1
              // Create a new art layer containing text
              var FirstLayer = newDoc.artLayers.add()
              FirstLayer.kind = LayerKind.TEXT
              
              //Set  the contents
              var textItem = FirstLayer .textItem
              textItem.contents = "Hello, World!"
              
              textItem.position = [100, 100]
              
              ///////////////////////////////////////////////////////Layer2
              
              var myFile = new File('~/Desktop/s_n.jpg');
              placeSmartObject(myFile);
              // place with put the image in the center of the document
              // so move to where we want it
              positionLayer( app.activeDocument.activeLayer, 200, 200 );
               
              /*  // you do not really need to release the references
                   // They will be released when the script ends
              //Release Refrences
              newDoc = null
              FirstLayer = null
              textItemRef = null
              */
              
              function placeSmartObject(fileRef){
              //create a new smart object  layer using a file
                   try { 
                        var desc = new ActionDescriptor();
                             desc.putPath( charIDToTypeID( "null" ), new File( fileRef ) );
                            desc.putEnumerated( charIDToTypeID( "FTcs" ), charIDToTypeID( "QCSt" ),charIDToTypeID( "Qcsa" ));
                            desc.putUnitDouble( charIDToTypeID( "Wdth" ),charIDToTypeID( "#Prc" ), 100 );
                            desc.putUnitDouble( charIDToTypeID( "Hght" ), charIDToTypeID( "#Prc" ), 100 );
                            desc.putUnitDouble( charIDToTypeID( "Angl" ), charIDToTypeID( "#Ang" ), 0 );
                            desc.putBoolean( charIDToTypeID( "Lnkd" ), true );
                             executeAction( charIDToTypeID( "Plc " ), desc, DialogModes.NO );
                             activeDocument.activeLayer.resize(100 ,100,AnchorPosition.MIDDLECENTER);
                    } catch (e) {
                if (!e.toString().match(/Place.+is not currently available/)) {
                    throw e;
                    }
                }
              };
              function positionLayer( lyr, x, y ){// layerObject, Number, Number
                   // if can not move layer return
                   if(lyr.iisBackgroundLayer||lyr.positionLocked) return
                   // get the layer bounds
                   var layerBounds = lyr.bounds;
                   // get top left position
                   var layerX = layerBounds[0].value;
                   var layerY = layerBounds[1].value;
                   // the difference between where layer needs to be and is now
                   var deltaX = x-layerX;
                   var deltaY = y-layerY;
                   // move the layer into position
                   lyr.translate (deltaX, deltaY);
              }
              
              
              1 person found this helpful
              • 4. Re: scripting newbee: How can I import a jpg to my document layer?
                JohnDrach13 Level 1

                This works great. I'm not exactly sure how it works. I've been checking out the code.

                Is there a way to slim this code down by not making the layer a smart layer?

                • 5. Re: scripting newbee: How can I import a jpg to my document layer?
                  Michael L Hale Level 5

                  JohnDrach13 wrote:

                   

                  Is there a way to slim this code down by not making the layer a smart layer?

                  No, in fact, because Photoshop creates the smart object when you use the place menu item, it would take more code not to have the layer a smart object. You would either have to add a few more lines to rasterize the smart object after it is place or a lot more code needed not to use place but to open the file as a document then copy the layer(s) over to the target document.

                  • 6. Re: scripting newbee: How can I import a jpg to my document layer?
                    JohnDrach13 Level 1

                    So is it possible to reuse this function again and again to place other graphics?

                    • 7. Re: scripting newbee: How can I import a jpg to my document layer?
                      Michael L Hale Level 5

                      yes, you can use the placeSmartObject function to place as many layers as you need. And the positionLayer function to move the layers into position.

                      • 8. Re: scripting newbee: How can I import a jpg to my document layer?
                        JohnDrach13 Level 1

                        Hey thanks for the info.

                         

                        Also have you used this plugin?

                        If so do yu have any thoughts on how well it works?

                         

                        http://blogs.adobe.com/crawlspace/2006/05/installing_and_1.html

                        • 9. Re: scripting newbee: How can I import a jpg to my document layer?
                          JJMack Most Valuable Participant

                          In my first append I told you that you might find my "Photo Collage Toolkit"  useful. The Scripts in that package use Place to populate templates with your image. Not only that it uses Alpha Channels to position, resize and Mask your images.  Scripting can present challenges and Photoshop is still evolving.  It was very hard to come up with code that worked for CS2, CS3 and CS5 because of changes made to Photoshop and Photoshop's scripting support.

                           

                          Smart Objects are good things you can transform them over and over again without accumulating image quality loss.  Masking effectively crops you image to your template image location, shape and size without actually cropping the image. You can always re-transform image to tweak their positioning and composition. Alpha channels and selections are the same thing. So you can use them as selections to add layer mask to make a virtual crop and use the selection to align layers to. With some work you can get the size of a placed image and the bounds of an alpha channel so you can transform the smart object image layer to fit the alpha channel well. 

                           

                          You seem to be new to Photoshop scripting at times its a bit tricky often you have to resort to using ScriptListener code and from time to time I have to consult with my good friend Rube Goldberg for I don't know javascript I only hack at it. Still you might get some ideas reading the scripts in my Photo Collage Toolkit I feel they do most of what you want to do.

                          • 10. Re: scripting newbee: How can I import a jpg to my document layer?
                            JohnDrach13 Level 1

                            I am pretty good at Action Script so I thught I would give Photoshop scripting atry as I use it everyday but I am finding it hard to get a hang of and I'm left wondering if its worth learnng.

                             

                            I took a look at your tool kit but I was a little lost in the code. I'll have to spend some more time looking through and experimenting.

                            • 11. Re: scripting newbee: How can I import a jpg to my document layer?
                              JJMack Most Valuable Participant

                              JohnDrach13 wrote:

                               

                              I thught I would give Photoshop scripting a try as I use it everyday but I am finding it hard to get a hang of and I'm left wondering if its worth learnng.

                               

                              The 64 dollar question.  I'll never become as good as Paul, Mike, xbytor, and others here.  Its great that they are here and always seem willing and eager to help others.  You question is hard to answer for as you know its not easy and will take a lot of time and work to learn. Where Actions are easy. However actions may  also be poor fit your work flow and work well for you but used by other harm the hard work for their workflow is different. Actions can also not do thing and not use logic. However Actions can also use scripts. So with a little bit of scripting it is possible to add some logic and do things in actions you never thought was possible. You will also think more about the actions you create and as a result make more useful actions.

                               

                              I put together a little package on crafting actions which contains four text files where I try to provide you with helpful tips from the knowledge I gained over the years.  Also included are a dozen utility scripts I wrote to be used within actions.  Ten are very small and easy to read and understand. Some are straight forward and just do some logical thing you can not do  just recording steps. Others are used twice in an Action  they are like a save and restore functions used in programming.  Use in the beginning of you action the save some Photoshop state information.   The action is then able to change the those states and at the end of the action restore the  document to its original state.

                               

                              So for me my answer was it was worth learning where experts willing to help hung out and where code and scripts could be downloaded from for I believe in reuse and I can cut and paste.  As I wrote I only hack at scripting I have a good programming background but don't really know javascript or object orientated programming. I'm from the old school dated but not afraid a fearless hacker.

                               

                              Crafting Actions Package

                              Contains
                              • Action Actions Palette Tips.txt
                              • Action Creation Guidelines.txt
                              • Action Dealing with Image Size.txt
                              • Action Enhanced via Scripted Photoshop Functions.txt
                              • CraftedActions.atn Sample Action set includes an example Watermarking action
                              • Sample Actions.txt Photoshop CraftedActions set saved as a text file. I also added som comments by hand.
                              • 12 Scripts for actions
                              Download
                              • 12. Re: scripting newbee: How can I import a jpg to my document layer?
                                Michael L Hale Level 5

                                JohnDrach13 wrote:

                                 

                                Also have you used this plugin?

                                I use that plug-in all the time. The placeSmartObject function I posted is from scriptlistener. I just cleaned it up a little and converted it into a function.

                                 

                                I do a little ActionScript and to me it is very similar to javascript. I would guess that the main problem you are having is understand the Photoshop Object Model. I think that even web developers with a good background in javascript have trouble at first scripting Photoshop because of the different Object Model used. I would suggest that you have a look at the Photoshop Javascript Reference pdf that ships with Photoshop.