Skip to main content
Known Participant
April 5, 2018
Answered

Background layer to file name script.

  • April 5, 2018
  • 2 replies
  • 3359 views

Hello!

I'd like to create a script to rename my background layer to the document filename without the extension.

This script works but it creates a text layer instead of converting the background layer to layer with document name.

So I could use some help in knowing what I have to change to make it work.

Let me know!
Thanks!

// this script is a variation of the script addTimeStamp.js that is installed with PH7

if ( documents.length > 0 )

{

var originalDialogMode = app.displayDialogs;

app.displayDialogs = DialogModes.ERROR;

var originalRulerUnits = preferences.rulerUnits;

preferences.rulerUnits = Units.PIXELS;

try

{

var docRef = activeDocument;

// Now create a text layer at the front

var myLayerRef = docRef.artLayers.add();

myLayerRef.kind = LayerKind.TEXT;

myLayerRef.name = "Filename";

var myTextRef = myLayerRef.textItem;

// strip the extension off

var fileNameNoExtension = docRef.name;

fileNameNoExtension = fileNameNoExtension.split( "." );

if ( fileNameNoExtension.length > 1 ) {

fileNameNoExtension.length--;

}

fileNameNoExtension = fileNameNoExtension.join(".");

myTextRef.contents = fileNameNoExtension;

// off set the text to be in the middle

myTextRef.position = new Array( docRef.width / 2, docRef.height / 2 );

myTextRef.size = 20;

}

catch( e )

{

// An error occurred. Restore ruler units, then propagate the error back

// to the user

preferences.rulerUnits = originalRulerUnits;

        app.displayDialogs = originalDialogMode;

throw e;

}

// Everything went Ok. Restore ruler units

preferences.rulerUnits = originalRulerUnits;

app.displayDialogs = originalDialogMode;

}

else

{

alert( "You must have a document open to add the filename!" );

}

This topic has been closed for replies.
Correct answer r-bin

var n = app.activeDocument.name.lastIndexOf(".");

app.activeDocument.backgroundLayer.name = n>=0?app.activeDocument.name.substr(0, n):app.activeDocument.name;

2 replies

Stephen Marsh
Community Expert
Community Expert
January 21, 2022
r-binCorrect answer
Legend
April 5, 2018

var n = app.activeDocument.name.lastIndexOf(".");

app.activeDocument.backgroundLayer.name = n>=0?app.activeDocument.name.substr(0, n):app.activeDocument.name;

Known Participant
April 5, 2018

Thanks! I appreciate it!

Kukurykus
Legend
April 5, 2018

If you do, mark his reply as correct solution