extendscript. how to save artlayer as png

Viewed 28

How can i save a ArtLayer as a png file? Are there any Action APIs I can use?

var layer = activeDocument.layers[2];
layer.copy();
var myDoc = app.documents.add(2000, 1000, 72, 'export-demo'); 
myDoc.paste();
var type = new PNGSaveOptions();
var fileSpec = new File("e:/ps/" + layer.name + ".png");
myDoc.saveAs(fileSpec, type);
1 Answers

Please note: I don't have the rep to comment and ask for more details. So I figured that I would just post the answer that I know.

There would be a few ways to accomplish this. But the easiest way that I've found to do this is to turn off the visibility of all other layers, then export a PNG. This would look something like this:

#target photoshop

var activeDoc = app.activeDocument;
var layers = activeDoc.layers;
var focusLayer = layers[ 2 ];
var visibleLayers = [];

for ( var i = 0; i < layers.length; i++ ) {
    // Add visible layers to array so they can be turned back on after export
    if ( layers[ i ].visible ) visibleLayers.push( layers[ i ] );

    // Turn off visibility of all layers except the focus layer
    if ( layers[ i ] !== focusLayer ) layers[ i ].visible = false;
}

// Export PNG * Change options to your liking
var filepath = "e:/ps/" + layer.name + ".png";
var file = File( filepath );

var exportOptions = new ExportOptionsSaveForWeb();
    exportOptions.format = SaveDocumentType.PNG;
    exportOptions.PNG8 = false; // false = PNG-24
    exportOptions.transparency = true; // true = transparent
    exportOptions.interlaced = false; // true = interlacing on
    exportOptions.includeProfile = false; // false = don't embedd ICC profile

activeDoc.exportDocument(file, ExportType.SAVEFORWEB, exportOptions);

// Turn visible layers back on
for ( var i = 0; i < visibleLayers.length; i++ ) {
    visibleLayers[ i ].visible = true;
}

The downside to this method is that it only exports to the size of the PSD and does not crop to the layer image dimensions.

Related