Photoshop script how to add image to a layer - photoshop

How can I grab an image by its location on my local machine and insert it into a layer with extendscript?
var doc = app.documents.add();
var layer = doc.artLayers.add();
var img = new File('~/Desktop/tanks.png');
layer.image = img; //I want to add the image to this layer
All I can seem to do is open the image as a background which creates a new photoshop doc in the process;
var opened = open(img);
But what I would like to achieve is to open multiple images into the same doc as multiple layers. Can this be done?

Open each of the images you want to consolidate using the open method you found. Then cycle through the open document and use the duplicate method on the art layer object to copy all the layers to a single target document. See the code snippet below for copying a single layer image to a new doc.
//copy the layer into the target document
app.activeDocument = pSourceDocument;
pSourceDocument.artLayers[0].duplicate(pTargetDocument);

I found a very useful script for doing this here https://forums.adobe.com/message/3946944#3946944
I took the piece of this script and it worked for me. First of all, you need to convert the layer which contents you want to replace with the image to a Smart Object (in other case contents of the layer can't be replaced by scripts). To do so, open the file you want to modificate in Photoshop, select the layer, click Layer > Smart Objects > Group into New Smart Object. Now this layer is a Smart Object.
Then create a script with the following code:
var replacementFile = new File("X:/file.jpg");
var theLayer = app.documents[0].artLayers.getByName("targetLayer");
theLayer = replaceContents(replacementFile);
////// replace contents //////
function replaceContents (newFile) {
// =======================================================
var idplacedLayerReplaceContents = stringIDToTypeID( "placedLayerReplaceContents" );
var desc3 = new ActionDescriptor();
var idnull = charIDToTypeID( "null" );
desc3.putPath( idnull, new File( newFile ) );
var idPgNm = charIDToTypeID( "PgNm" );
desc3.putInteger( idPgNm, 1 );
executeAction( idplacedLayerReplaceContents, desc3, DialogModes.NO );
return app.activeDocument.activeLayer
};

Related

"Geodatabase field exists: fid" loading shape file

I'm attempting to create a feature layer in ARC GIS using a shape file but I'm getting the following exception when trying to open the shape file with ShapefileFeatureTable.OpenAsync
{"Geodatabase field exists: fid"}
var shapeFileFeatureTable = ShapefileFeatureTable.OpenAsync(#"...\myshape.shp").Result;
fl = new FeatureLayer(shapeFileFeatureTable)
{
// Set the rendering mode of the feature layer to be dynamic (needed for extrusion to work).
RenderingMode = FeatureRenderingMode.Dynamic,
IsVisible = true,
};

Embed pdf content in pdf layer

I just registered. I try to address the following case:
Given a basic pdf (a simple, single raster image), I want to get to:
Create a pdf (empty initially), in which I create a layer, in which I embed the raster image of the input_pdf, and mark said layer as visible and not_printable.
Are there tools to do it?
Thanks for the tips.
Since you do not specify a language or a library you use, here it is a solution in C#:
// Extract the page content from the source file.
FileStream stream = File.OpenRead("input.pdf");
PDFFile source = new PDFFile(stream);
PDFPageContent pageContent = source.ExtractPageContent(0);
stream.Close();
PDFFixedDocument document = new PDFFixedDocument();
document.OptionalContentProperties = new PDFOptionalContentProperties();
PDFPage page = document.Pages.Add();
// Create an optional content group (layer) for the extracted page content.
PDFOptionalContentGroup ocg = new PDFOptionalContentGroup();
ocg.Name = "Embedded page";
ocg.VisibilityState = PDFOptionalContentGroupVisibilityState.AlwaysVisible;
ocg.PrintState = PDFOptionalContentGroupPrintState.NeverPrint;
// Draw the extracted page content in the layer
page.Canvas.BeginOptionalContentGroup(ocg);
page.Canvas.DrawFormXObject(pageContent, 0, 0, page.Width, page.Height);
page.Canvas.EndOptionalContentGroup();
// Build the display tree for the optional content
PDFOptionalContentDisplayTreeNode ocgNode = new PDFOptionalContentDisplayTreeNode(ocg);
document.OptionalContentProperties.DisplayTree.Nodes.Add(ocgNode);
using (FileStream output = File.Create("EmbedPageAsLayer.pdf"))
{
document.Save(output);
}
The output PDF file is available here: https://github.com/o2solutions/pdf4net/blob/master/GettingStarted/EmbedPageAsLayer/EmbedPageAsLayer.pdf

Insert Image as New Layer in Photoshop

I want create new layer with image in it. I didn't find anything useful or correct answer for this question.
What I'm doing now is:
var oldActive = app.activeDocument;
app.load(new File(path)); //load it into documents
var tempDoc = app.activeDocument;
// backFile.resizeImage(width, height); //resize image into given size i.e 640x480
tempDoc.selection.selectAll();
tempDoc.selection.copy(); //copy image into clipboard
tempDoc.close(SaveOptions.DONOTSAVECHANGES); //close image without saving changes
oldActive.paste(); //paste selection into your document
Code above opens new document/tab and doing simple logic, then closes new document and brings me back to the old one and pastes image what I need.
I don't like this approach because user can see how documents blinking/opens/closes.
I'm looking for a simple way which allows insert image into current active Document without opening new ones.
Ok guys. So this is correct way to paste image by path into current activeDocument without opening new ones:
var sourceFile= new File(path);
var idPlc = charIDToTypeID( "Plc " );
var desc3 = new ActionDescriptor();
var idnull = charIDToTypeID( "null" );
desc3.putPath( idnull, sourceFile);
var idFTcs = charIDToTypeID( "FTcs" );
var idQCSt = charIDToTypeID( "QCSt" );
var idQcsa = charIDToTypeID( "Qcsa" );
desc3.putEnumerated( idFTcs, idQCSt, idQcsa );
executeAction( idPlc, desc3, DialogModes.NO );

cannot load image in isolated storage when creating IconicTile

I'm trying to create IconicTile using image saved on isolated storage.
At first, I saved image to isolated storage.
// bitmap is Stream of image source (e.g. from PhotoChooserTask)
var wbmp = new WriteableBitmap(bitmap);
var file = "Shared/ShellContent/IconicTile.png";
// when file exists, delete it
if (storage.FileExists(file))
{
storage.DeleteFile(file);
}
using (var isoFileStream = new IsolatedStorageFileStream(file, FileMode.Create, storage))
{
// use ToolStackPNGWriterExtensions
wbmp.WritePNG(isoFileStream);
}
And I have confirmed PNG file is successfully created using Isostorage Explorer Tools.
Then I try to create IconicTile.
var initialData = new IconicTileData
{
BackgroundColor = SelectedColor,
IconImage = new Uri("isostore:/Shared/ShellContent/IconicTile.png", UriKind.Absolute),
Title = tbTitle.Text,
WideContent1 = tbWideContent1.Text,
WideContent2 = tbWideContent2.Text,
WideContent3 = tbWideContent3.Text
};
var uri = string.Format("/SecondaryPage.xaml");
var TileToFind = ShellTile.ActiveTiles.FirstOrDefault(x => x.NavigationUri.ToString().Contains(uri));
if (TileToFind == null)
ShellTile.Create(new Uri(uri, UriKind.Relative), initialData, true);
else
TileToFind.Update(initialData);
But image in the created tile are white.
(I'd like to attach image but my reputation is too low. Sorry.)
I tried not only PNG format but also JPG format, but neither doesn't work.
Is there anyway to create IconicTile using image on IsolatedStorage?
The iconic tile format expects a transparent background, based on your comment at the first line (PhotoChooserTask), I suspect you're using some type of image with no transparency.

Function to show/hide layer with Photoshop script (JSX)

I am writing a script that will loop through layers, trim them and export. So far I have most of all the element I need to complete this script. The only thing I can't find is how to show/hide an individual layer. I've found functions to show/hide all layers but nothing for one single layer.
///////////////////////////////////////////////////////////////////////////////
// selectAllLayers - select all layers (Select > All Layers)
///////////////////////////////////////////////////////////////////////////////
function selectAllLayers() {
var ref = new ActionReference();
ref.putEnumerated(cTID('Lyr '), cTID('Ordn'), cTID('Trgt'));
var desc = new ActionDescriptor();
desc.putReference(cTID('null'), ref);
executeAction(sTID('selectAllLayers'), desc, DialogModes.NO);
}
///////////////////////////////////////////////////////////////////////////////
// hideLayers - hide all selected layers (Layer > Hide Layers)
///////////////////////////////////////////////////////////////////////////////
function hideLayers() {
var ref = new ActionReference();
ref.putEnumerated(cTID('Lyr '), cTID('Ordn'), cTID('Trgt'));
var list = new ActionList();
list.putReference(ref);
var desc = new ActionDescriptor();
desc.putList(cTID('null'), list);
executeAction(cTID('Hd '), desc, DialogModes.NO);
}
function cTID(s) {return app.charIDToTypeID(s);}
function sTID(s) {return app.stringIDToTypeID(s);}
Any ideas?
The Layer object has a .visible boolean property which you can use to control visibility for each layer individually:
// make active layer invisible
app.activeDocument.activeLayer.visible = false;
or
// make active layer visible
app.activeDocument.activeLayer.visible = true;
or even toggle visibility for the selected/active layer:
app.activeDocument.activeLayer.visible = !app.activeDocument.activeLayer.visible;
or loop through what layers you need and toggle their visibility:
//example hides odd layers while showing even layers, based on their index
var doc = app.activeDocument;
for(var i = 0 ; i < doc.layers.length;i++){
doc.layers[i].visible = (i % 2 == 0);
}
I suggest having a looks either in the Photoshop CS5 Javascript Reference (PDF link) or in ExtendScript Toolkit's Object Model Viewer.
You can access it via Help > Object Model Viewer and select the Adobe Photoshop CS5 Object Library from the browser combobox/list to the list of classes available in the Photoshop DOM.