Question

I'm attempting to use the following Photoshop CC JavaScript script to take all the layers in a PSD file, and save them as separate files:

var file = new File('path/to/file.psd'),
  docRef = open(file),
  i,
  len,
  duplicateLayer,
  dimens,
  newDoc,
  newLayer;

for (var i = 0, len = docRef.artLayers.length; i < len; i += 1) {
  duplicateLayer = docRef.artLayers[i].duplicate();
  //duplicateLayer.(RasterizeType.ENTIRELAYER);
  duplicateLayer.copy();
  dimens = duplicateLayer.bounds;

  newDoc = documents.add(dimens[2] - dimens[0], dimens[3] - dimens[1], 300,
                         'exportedLayer' + i, NewDocumentMode.RGB,
                         DocumentFill.TRANSPARENT);
  newLayer = newDoc.artLayers.add();
  newDoc.paste();
}

Unfortunately, it's not working. I'm getting all sorts of errors, mainly one about how I can only duplicate layers from the frontmost document. What does this mean?

I apologize, but I'm a total beginner when it comes to Photoshop, so any help on how I can make the above script do what I want would be greatly appreciated.

Thank you all very much.

Was it helpful?

Solution

var file = new File('path/to/file.psd'),
  docRef = open(file),
  i,
  len,
  duplicateLayer,
  dimens,
  newDoc,
  newLayer,
  layers = [];

for (var i = 0, len = docRef.artLayers.length; i < len; i += 1) {
  layers[i] = docRef.artLayers[i];
}
for (var i = 0, len = layers.length; i < len; i += 1) {
  app.activeDocument = docRef;
  duplicateLayer = layers[i].duplicate();
  duplicateLayer.rasterize(RasterizeType.ENTIRELAYER);
  dimens = duplicateLayer.bounds;
  duplicateLayer.cut();

  newDoc = documents.add(dimens[2] - dimens[0], dimens[3] - dimens[1], 300,
                         'exportedLayer' + i, NewDocumentMode.RGB,
                         DocumentFill.TRANSPARENT);
  newLayer = newDoc.artLayers.add();
  app.activeDocument = newDoc;
  newDoc.paste();
}

First, note I set the focus to your original document for every layer I create. Second, I kept a reference to all the layers, as playing around with new layers may mess up your cycling through the original layers. Third, I used cut rather than copy, to delete the newly added layers. And... voila.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top