Scripting Photoshop with JavaScript

Did you know you can script common Photoshop tasks with JavaScript? Now you do :)

IDE even

When you install PS it comes with a tool called ExtendScript Toolkit, which is an IDE to write scripts - with debugger, console to try stuff out etc.

To launch I just type "Extend" in Spotlight search. I'm guessing it's got to be somewhere in Program Files\Adobe on Windows too.

Here it is:

Getting started

As you can see on the screenshot, it's easy to get started.

app; // the Photoshop application
app.documents; // collection of open files/documents
app.documents[0]; // the first file
app.documents[0].name; // the first file's filename
app.documents[0].layers.length // how many layers in the doc

Running your script

There's a green "play" button in the IDE, it runs your script.

The directive:

#target photoshop

tells the engine that this is a photoshop script. Apparently you can script other Adobe products too.

If you don't have photoshop open, this directive will open it for you. Then it's all you - open a file, hide a layer, save, close, etc

Also if you save your script file with a .jsx extension, you can put in on the desktop and double-click it. Easy as pie.

And finally, if you put it in the appropriate directory (PSDIR/Presets/Scripts), it will show up in Photoshop menus under File -> Scripts

Docs

A *Yahoo* search will find the docs for you right here:
http://www.adobe.com/devnet/photoshop/scripting.html

There's a scripting guide (nice) and a JavaScript reference (the exact object/method names).

There are also VBScript and AppleScript references in case you insist on writing non-portable scripts :)

Generating code

Getting started with a completely new API can be a little uphill-y walk. For me it was especially so when it comes to saving a file with all the options. Worry not, you can generate code too!

Check the scripting guide where it talks about "The ScriptListener Plug-In". It's a plugin that you already have, you just copy it to to the appropriate directory to activate it and then restart PS.

Then whatever you do in photoshop will generate code in a .log file on your desktop. Then you can go back and cleanup that file (it generates somewhat verbose code) and get the parts you need.

Example - Mojotune chords

So for this "JavaScript is Everywhere" talk I gave this year at OSCON (slides) I came up (with a friend's help) with a sample application that I ported to different environments.

The core of it is m.js (m as in mojo, m as in (data) model). It's a portable piece of JavaScript that knows a lot about guitar chords. I wanted to generate nice PNGs with the data from the chord model. So - Photoshop scripting.

The document template is shown here with three visible layers.

This is the guitar's neck and each dot is where you press. The template has a layer for each dot (each fret on each string), appropriately named:

The task is to get the chord configuration, show the corresponding layers and save the file with the chord name as filename.

So I did this manually (while recording the generated code): show a layer, save the file.

Show/hide layers

The generated code for showing a layer looked like an oddly indented piece of overhead:

/////// GENERATED - DON'T!

// =======================================================
var idShw = charIDToTypeID( "Shw " );
    var desc2 = new ActionDescriptor();
    var idnull = charIDToTypeID( "null" );
        var list1 = new ActionList();
            var ref1 = new ActionReference();
            var idLyr = charIDToTypeID( "Lyr " );
            ref1.putName( idLyr, "11" );
        list1.putReference( ref1 );
    desc2.putList( idnull, list1 );
executeAction( idShw, desc2, DialogModes.NO );

This goes out the door since it can be replaced with:

app.documents[0].layers.getByName('11').visible = true;

(11 means first fret on first string)

Save for web

The generated code for saving a PNG is even worse, but I simply reindented it and shoved in into a function and that was that.

function saveFile(filename) {
    // the following is mostly auto-generated by PS 
    var idExpr = charIDToTypeID( "Expr" );
    var desc14 = new ActionDescriptor();

    /// 200 more lines...
}

All the chords

Finally the part that I actually had to write myself.

Directives:

#target photoshop
#include "../../lib/m.js"

Notice how easy it is to include a JS file, in my case the data model m.js?

Singe var pattern:

var data, 
    i, c, v, 
    layer,
    layers = app.documents[0].layers;

The mojo object comes from m.js. How it works is not very important. The thing is it has a mojo.guitar.getChord() method. You give it a chord name and it returns an array - which fret needs to be pressed on each string.

// mojo.guitar.getChord('Am')
// returns [ignore, 0, 1, 2, 2, 0, x]

All we need to do then is loop though the array and show the layers. Then save the file (e.g. Am.png) and then hide the same layers so they don't interfere the next chord. So this is the end result which generates all the chords m.js knows about:

for (c = 0; c < mojo.prettytones.length; c++) {
    for (v = 0; v < mojo.allchords.length; v++) {
        chord = mojo.prettytones[c].split('/')[0];
        chord += mojo.allchords[v];
        data = mojo.guitar.getChord(chord);
        for (i = 1; i <= 6; i++) {
            layer = "" + i + data[i];
            layers.getByName(layer).visible = true;
        }
        chord = chord.replace('#', '-sharp');
        saveFile('~/stoyan/mojo/chords/images/' + chord + '.png');
        for (i = 1; i <= 6; i++) {
            layer = "" + i + data[i];
            layers.getByName(layer).visible = false;
        }
    }
}

Run it and that's it - a bunch of PNG images are written.

Linkies

  • mojotune.jsx - The final script
  • m.js - the data model ("Check out Guitar George, he knows all the chords" - Dire Straits)
  • images - the generated chord PNGs
  • JS everywhere: slides and code

55 Responses to “Scripting Photoshop with JavaScript”

  1. Michael J Rubillo Says:

    Photoshop Scripting is a very powerful tool. I just made a video to show a few friends that enjoy Photoshop what I have been able to do with it: http://www.youtube.com/watch?v=DmMCG5T_iGM

  2. JavaScript Magazine Blog for JSMag » Blog Archive » News roundup: vintageJS, accounting.js, spin.js Says:

    [...] Scripting Photoshop with JavaScript [...]

  3. Thomas Says:

    I’ve been scripting Photoshop for a while now using ExtendScript. But does anyone know of a way you can execute a script via the shell? The problem with ExtendScript is that you can’t integrate into your greater programming workflow.

  4. Four short links: 23 September 2011 | National Cyber Security Says:

    [...] Scripting Photoshop with Javascript — Javascript is the new BASIC. (via Brett Taylor) [...]

  5. Cheap PHP Script Says:

    You really make it appear so easy with your presentation but I find this matter to be really one thing which I think I would never understand. It seems too complex and extremely extensive for me. I am having a look ahead on your next put up, I will try to get the grasp of it!

  6. professional photo monitor Says:

    professional photo monitor…

    [...]JSPatterns.com » Blog Archive » Scripting Photoshop with JavaScript[...]…

  7. Army Knowledge Online Says:

    Gloriously expert position. I merely bumbled upon your post and desired to articulate that I have really relished understanding your blog articles.

  8. custom t shirt Says:

    http://www.yescustom.com/blog/site-like

  9. Vimax Brasil Says:

    Intriguing blogging site by an classy templates, it could be better if virtually all the present material on your blog is made unique with intriguing topics that will give you far more customers to your internet site.

  10. Marna Leef Says:

    Time for to put this into action!

  11. Keith Sturchio Says:

    Is there something wrong with the CSS here? It all looks orange and I can barely read the article?

  12. Quick Weight Loss Center Says:

    Quickest Way to Lose Weight…

    [...]right here are several references to internet pages that we link to because we believe they’re definitely worth visiting[...]…

  13. stock image Says:

    Howdy I am so thrilled I found your webpage, I really found you by mistake, while I was browsing on Bing for something else, Anyways I am here now and would just like to say cheers for a tremendous post and a all round thrilling blog (I also love the theme/design), I don’t have time to read through it all at the minute but I have book-marked it and also added in your RSS feeds, so when I have time I will be back to read a lot more, Please do keep up the great job.

  14. misWinding Says:

    +1

  15. Alexia Says:

    yeah, i totally agree with you.http://www.musicaluansantana.net

  16. vibrators Says:

    Normally I do not learn post on blogs, but I would like to say that
    this write-up very compelled me to try and do so!

    Your writing style has been surprised me. Thanks, very nice article.

  17. kompresory klimatyzacji warszawa Says:

    I have learn several just right stuff here.

    Definitely value bookmarking for revisiting.
    I wonder how so much attempt you put to make this sort of wonderful informative
    web site.

  18. nutrition Says:

    I used to be suggested this website by means of my cousin. I am no longer sure whether this post is written by means of him as nobody else recognize such certain approximately my problem. You’re incredible! Thanks!

  19. cicerone.org Says:

    Heya i am for the primary time here. I came across this board and I in finding It truly useful & it helped me out a lot.
    I am hoping to present something back and aid others like you helped me.

  20. guitarchords Says:

    Hmm, i am in the process of creating diagrams of guitar chords for my guitar website and doing them one by one in Photshop doesn’t appeal to me so I am going to give this a try. As a one-time programmer and a guitar player I should be able to make use of it, so thanks.

  21. nice art Says:

    My brother suggested I would possibly like this website. He was once totally right. This post actually made my day. You can not imagine simply how much time I had spent for this information! Thank you!

  22. Google Says:

    Every when in a while we select blogs that we read. Listed below would be the most current sites that we pick out

  23. steroids legal Says:

    gгeat pointѕ altοgether, yоu ѕіmply gainеd a new гeаdеr.
    What cοuld you recοmmеnԁ аbout уour publiѕh that you maԁe а few
    days аgо? Any ѕuгe?

  24. code psn Says:

    In addition, one needs to take a look at various discounts on this
    card if available. What’s more, having electronic access to outpatient records online makes it possible for hospital-based clinicians, such as emergency department physicians, to make the most appropriate care decisions when patients present for treatment. Hardly surprising then that fans feel short changed.

  25. Garage Doors Titusville Says:

    Hi, i believe that i noticed you visited my web site so i came to go back the desire?.I’m trying to in finding things to enhance my site!I suppose its good enough to make use of some of your concepts!!

  26. Phyllis Says:

    Hey There. I found your blo using msn. This iis an extfemely well written article.
    I’ll make sure to bookmark it and return to read more of your useful info.
    Thanks for the post. I will certainly comeback.

  27. stiebel eltron tankless electric water heater Says:

    What’s up, I want to subscribe for this blog to
    obtain newest updates, thus where can i do it please help out.

  28. Wedding shoes Says:

    Hello to all, how is the whole thing, I think every one is getting more from this web page, and your
    views are nice in support of new people.

  29. home renovation services Says:

    When some one searches for his essential thing, thus he/she desires to be available that in detail, thus that
    thing is maintained over here.

    Feel free to surf to my web-site – home renovation services

  30. cheap adidas soccer jerseys Says:

    Make her hand in a source in person by the old body.”The big fiesta takes charge of a delight with unexpected good news way:”That all these handed over to too up elder, at our snake clan, the person who can advise to take to greatly get generally at present’s only having you is getting older, as long as greatly getting generally can wear to think for whole clanses, ignore she has what idea, we all will no postmortems.”The imperial concubine of the She a wave hand way:”This is the matter in the o

  31. http://omnistech.com/Images/isabelmarantlondon.asp Says:

    alternative routes “on the next paragraphs choices when you begin, says mary Mongo over at Parsons, “school’s not necessarily quite for all of us. economic climate just looking to get a job in the style area of trading not a job to bec,isabel marant outlet.ome brand possibly don’t need to go your education, you ought to work as a dressmaker as well as patternmaker, the best thing is probably to obtain an int,isabel marant dicker boots.ernship at your trendy store and as well as come up. yep, Siy

  32. Top Eleven Tocken Hacks Says:

    Start promoting these fundamental, universal triggers in your
    marketing. 21 23 Houston Texans (4-6) The defense is just incredibly bad.
    Stefano Langone and Jacob Lusk joined Toscano in the bottom three.

    Check out my web-site Top Eleven Tocken Hacks

  33. Marcos Says:

    advent wreath combines the ancient symbols of the wreath (victory) and the candle.
    Public Areas Keepers are responsible for
    maintaining the areas where visitors come to look at the animals.
    Such inspiration leads to collective efforts, the results of which turn out to
    be more than the sum of individual efforts.

    Feel free to surf to my web site :: hay day cheats (Marcos)

  34. pirater Wifi gratuit Says:

    The configuration of Bluetooth present in the mobile is 2.
    Google just announced their biggest purchase ever, picking up Motorola Mobility for $12.
    These are incredibly exciting times for the mobile communications industry with amazing advancements being made in the
    field that will change the way the entire world communicates by giving
    consumers more freedom and making wireless costs
    more affordable to everyone.

    Also visit my homepage; pirater Wifi gratuit

  35. New Era cap -cut | Медицинские консультации Says:

    [...] -cut, your mids and also the high-tops. It also also comes in numerous colors, designs, designs and also kinds. The particular just about all whitened and all sorts of dark sets will be the most typical and most well-liked types with the Nike Air flow Force Versions.google_hints = «Business,Nike No cost Run Your five.3 Guys inexpensive Search , ww»;Whilst purchasing the right playing golf clothing for your body is very important, buying the proper sets on your feet is additionally crucial. Luckily Nike provides your back presently there as well. They have an entire line of men抯 as well as women抯 sporting activities socks along with shoes. Nike socks consist of DriFIT Total Support Move Leading Hosiery,New Era cap,Moncler jacket user interface The style displays t, DriFIT Technological Base No-Show Clothes,New Era snapbacks, along with Anklet Clothes. Nike抯 footwear line is quite impressive also. It contains: Air flow Concern Playing golf Shoes or boots,Moncler online browse before buying, Atmosphere Greatest extent Double N Golfing Shoes or boots, Atmosphere Max Advantage II, Shox Golfing Shoes,Moncler jacket did even though to fast, SP-5 Golfing Sneakers, SP-5.5 Golfing Sneakers, SP-6 Spikeless Playing golf shoes or boots, SP-3, SP-4, SP-5 Spikeless Playing golf Shoes, SP-5.Five LX Laid-back Spikeless Golf Shoes or boots,New Era sale, LX Golfing Footwear, SP-6 The second Playing golf Sneakers, and SP-8 TW Tour Playing golf Footwear.Baby’s initial Nike’s may be totally adorable, but are these people needed? As outlined by most professionals – and not just modern types nevertheless for a minimum of the final thirty years * babies do not require shoes till they may be way up along with travelling. Actually at that time, it’s great for the little tikes to go into a great deal of without footwear period so they get used to their particular equilibrium and how their own small toesies work.The corporation specializes in the gathering for girls and kids as well. Ladies Air flow Jordon抯 are successfully sturdy and quite a few trustworthy. They offer the particular support which a women participant would assume on the printed company. Nike抯 Dous for females provides the energy that women need to fly dunk in any individual. Women抯 Nike Dunks give you the best bouncing assistance. One will discover the coolest variety of Nike Air Jordan for Men and females game sneakers throughout Nike in which begins coming from $59.98 up to $399.98. Even for children, Nike provides the every bit as stunning and adorable series from the exact same price tags. They may be fairly reasonable to get with the comfort level they supply.Sneakers have always obtained their particular stick through the stars. Especially the costume sneaker. In 2010 will not be any different. Several brand new types had been presented on the prizes shoe which include some solid wood shoes worn through Heidi Klume and some a lot more treasure set sandals put on simply by Olivia Wilde. They were given seen since they wandered the carpet since photographs of their shoes or boots created headers the very next day. Of course, his or her footwear created the head lines.The next thirty day period of Next year is about to enter a stop, frosty and never dispersed, many women are still donning winter months boot styles, Nike Oxygen Max sneakers, behind that your inscription «UGG» boot styles inside the word snow. It turned out observed that all of China’s «UGG» is just one retailer, but now filled with little shelves with the «UGG» may be the story powering the particular snow footwear?Free of charge Manage A couple of is the better on the web shoes giving home gym workout shoesFamous due to the athletic shoes, NIKE (evident NI-KEY could be the 20th century sneakers that lifting the best Sports Shoes or boots on earth to brand new levels of outstanding capability and achievements. However are not just to the sports activity associated with modern day fashion Moncler online browse before buying [...]

  36. Jeux Steam Gratuit Says:

    But how can you get in on it if you’re on a Windows PC
    or a Mac. A lot of websites provide chances to get pleasure from such spare time activities.
    Now, you will never make anywhere close to even 50 USD with just this system alone, but for the minimum amount of work and effort
    it takes, who is complaining about some free money for games.

    Here is my web-site :: Jeux Steam Gratuit

  37. Fawzia Khan Says:

    Hello,
    i was studying about object oriented javascript. can u plz suggest me some simple websites (URLs) created using the object oriented javascript. Thank you in advance

  38. hats Says:

    I don’t know if it’s just me or if perhaps everybody
    else experiencing problems with your website. It appears like some of the written text
    on your posts are running off the screen. Can somebody else please
    provide feedback and let me know if this is happening to them as
    well? This may be a problem with my internet browser because I’ve had this
    happen before. Kudos

    my web page: hats

  39. 1 Says:

    Fastidious answer back in return of this issue with solid arguments
    and explaining all regarding that.

    Feel free to visit my web page … 1

  40. Childrens Place Coupons Says:

    This is a topic which is close to my heart…
    Many thanks! Exactly where are your contact details though?

  41. eldondhin.newsvine.com Says:

    I know this web page presents quality based articles or reviews and
    other stuff, is there any other website which presents these data in quality?

    Also visit my site; find computer support (eldondhin.newsvine.com)

  42. Kelle Says:

    A motivating discussion is worth comment. I
    do believe that you should publish more on this subject, it might not be a taboo subject but usually people do
    not discuss such topics. To the next! Kind regards!!

    My website Best IT Solutions (Kelle)

  43. Christopher Says:

    fantastic points altogether, you simply gained a emblem new
    reader. What might you suggest in regards to your publish that you simply
    made some days ago? Any positive?

    Also visit my webpage: New York City IT Services (Christopher)

  44. Jacquie Says:

    If you are going for most excellent contents like me, just pay a quick visit this site
    daily since it provides quality contents, thanks

    my blog – Panasonic Toughbook Computers, Jacquie,

  45. Manie Says:

    Hi! I’ve been following your web site for a long time now and
    finally got the bravery to go ahead and give you a shout out
    from Houston Texas! Just wanted to mention keep up the excellent job!

  46. Richie Says:

    Cancun possess many golf clubs with scenic places that
    are considered to be a few of the ideal courses in Mexico.
    In a lot of cases, relations can feel found inside the U.S.
    utilizing inexpensive services such as U.S. Search or other will mean.
    This excellent is a powerful contributing factor to values in the area.

    Check out my homepage … best honeymoon resort [Richie]

  47. gamefly Says:

    I am really grateful to the holder of this website who has shared this wonderful
    article at here.

  48. perfumes new york Says:

    Wow, this post is good, my younger sister is analyzing these things, thus I am going to convey her.

  49. Parajumpers Long Bear Says:

    We might give the Grinch the benefit of the doubt and assume that he is not so stupid as to actually believe this,Parajumpers Kodiak, but is just cleverly insulting all Moslems,Parajumpers Long Bear, and indeed all non-Christians and intelligent Christians,Parajumpers Outlet, in order to appeal to petty, ugly-minded Christian radicals. Amazingly I actually found a photo of this fine parajumpers kodiak women. But Agent Rigsby (Owain Yeoman) still hasnÂ’t admitted that he still has feelings f

  50. Anonymous Says:

    Attended the ultrasound at what I thought was about 7 weeks. “This interpretation may help us understand why both twinning and birth defects increase with maternal age,LANCEL MINI SAC PREMIER FLIRT CUIR FOULONNé – SAFRAN, as there may be a common mechanism.”The results of the research to be presented today may have important implications for fertility treatment,Sac porté main Lancel French Flair cuir – Noir, for instance when implementing a policy of single embryo transfer. Outside inv

  51. Parajumpers Long Bear Says:

    To let it dry faster, you may use a box fan. You will also need the business skills to support your operational skills. Do yo have pans to make yo wedding a festive one withot spending too mch of doas? The first step in investing in a Billiga Parajumpers cone stand is identifying what type of stand you want acquiring. Then, fill Parajumpers Long Bear in your Facebook and Twitter details before Parajumpers Jackets downloading all of the extensions you need to make the browser your own. Can You Ge

  52. Rosalyn Says:

    At this moment I am going to do my breakfast, later than having my breakfast coming ver again to read other news.

  53. http://www.lapitusa.es/news/louis-vuitton71.htm Says:

    Ultimate design nerd . Or obsessive compulsive? Jobs sweated the information in his life and work. He lived a spartan existence within the floors of his mansions, largely because he was not able to bring himself to chose just one sofa or bedframe. Definitions The terms “biological control” and it is abbreviated synonym “biocontrol” have been completely utilized in different fields of biology, specifically entomology and plant pathology. In entomology, it is utilized to describe the employment of

  54. Cheap Ralph Lauren Says:

    Even though there will still be many entities examining the planet out,Cheap Ralph Lauren outlet ell, most will commit to look elsewhere Whatthis means exactly is the fact that including,Discount Ralph Lauren, in gifts, something special to have a loved one quite often doesnot feel as worthy when it would not have a very certain amount of economic value The framework comes with a tall glass cube which has an overhang that extends well beyond the structure You don’t have to go on to Forks an addi

  55. เช่าชุดคอสเพลย์ Says:

    Magnificent beat ! I wish to apprentice while you amend your web site,
    how can i subscribe for a blog website? The account helped me a acceptable deal.
    I had been a little bit acquainted of this your broadcast provided bright clear idea

Leave a Reply