A log of interesting things made by Kunal Anand
Automating Photoshop with JavaScript
01/15/2007
I have been helping my parents create a dynamic web site for their family business. Part of the job entails transforming every page from a 77 megabyte PDF catalog into a web ready JPG. From a quick brainstorming session I came up with four different ways of doing image resizing:
- Munge with a Photoshop COM object
- Use JavaScript within Photoshop
- Play with Python/PIL and some PDF package
- Do it manually (unreasonable)
So I ended up going with option two, which was surprisingly awesome. Here is the source code from the whole thing. I start the script by initializing the necessary variables - page count and paths:
total_pages = 68;
full_document_path = "~/Project/Assets/catalog.pdf";
full_output_path = "~/Project/Assets/jpg/";
Now let's write a function that handles opening a specific page of a PDF:
function open_document(page) {
FileReference = new File(full_document_path);
PDFOpenOptions = new PDFOpenOptions();
PDFOpenOptions.page = page;
PDFOpenOptions.resolution = 72;
app.open(FileReference, PDFOpenOptions);
}
Since Photoshop cannot open all the pages of a PDF file, we have to manually determine what page requires resizing. In my case, just opening each page at 72 DPI is perfect (the original resolution is 600 DPI). Now let's write a function to save the document:
function save_document(page) {
jpgFile = new File(full_output_path + page + ".jpeg");
jpgSaveOptions = new JPEGSaveOptions();
jpgSaveOptions.embedColorProfile = true;
jpgSaveOptions.quality = 12;
app.activeDocument.saveAs(jpgFile, jpgSaveOptions, true, Extension.LOWERCASE);
}
Since the catalog products have a lot of detail, I set the JPG quality to the highest, which is 12. Let's go ahead and write our one-line function that closes the active document:
function close_document() {
app.activeDocument.close(SaveOptions.DONOTSAVECHANGES);
}
I did not really need to make a function around this, I just thought it was more convenient to call close_document than that whole string every time. With these functions, we can write the logic:
for (i=1; i<=total_pages; i++) {
open_document(i);
save_document(i);
close_document();
}
That iterates over the variable we initialized at the top of the script and we are in business. Throw this file into your /Photoshop/Presets/Scripts/ directory, open Photoshop, goto File > Scripts, select the script and enjoy watching JavaScript do all the work for you.
I am still figuring out the kinks in the Photoshop object model, but this route was definitely a time saver. I would recommend other efficiency junkies give this a shot.