Skip to main content
Known Participant
April 5, 2018
Answered

Background layer to file name script.

  • April 5, 2018
  • 2 replies
  • 3342 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
Adobe Expert
January 21, 2022
r-binCorrect answer
Brainiac
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
October 25, 2018

The script to use filename to rename the background layer no longer works in Photoshop cc2019.
Anybody know how to make it work in new version?

Thanks!

Stephen Marsh
Adobe Expert
January 21, 2022

I can tell is true, is not working anymore, I hope anyone know a new code to rename current layer to file name without the extension, thank you for anyone who can help.


You can use this more generic code, r-bin's was specifically for the Background layer and still works as originally intended:

 

app.activeDocument.activeLayer.name = app.activeDocument.name.replace(/\.[^\.]+$/, '');