Skip to main content
Familier with Photoshop
New Participant
January 8, 2020
Question

Using a Script to Add a File Name to an Image.

  • January 8, 2020
  • 7 replies
  • 23013 views

How to put file Name in file top left corner in file Using a Script to Add a File Name to an Image.

let me explain anybody experts.

7 replies

Jeffery Sanders
New Participant
July 29, 2023

Here it is, just as you asked for it, and then some! It's the GOLDENGUN of Photoshop name scripts; it will surely blow all others out of the water. Variables allow complete customization, and comments are plentiful for ease of editing.

Overall, the script will automatically center the filename and maximize the text size based on the limits you set, until it clips. It will also attempt to resize outputs automatically if you clip horizontally, as long as you keep reasonable values. The script offers three output options: filename, filename.extension, and path name. Additionally, you can select your font of choice from the comments, apply custom offsets from "auto center," and choose colors based on RGB values. Feel free to edit the Scaling Factors and other variables to achieve the exact output you desire, and verbose output is available as well. The variable for fonts has been improved with helpful comments, and I've added horizontal variable offsets that scale accordingly.

A special thanks to JJMack for the original script and the powerful tool, ChatGPT. Hopefully this helps someone, if you find it useful, please give me a thumbs up! If anyone wants to suggest additional features or finds any bugs, please let me know, and I will fix/add them ASAP.

#target photoshop // this command only works in Photoshop CS2 and higher
app.bringToFront();

if (!documents.length) {
  alert('There are no documents open.', 'No Document');
} else {
  // Call the main function wrapped in Document.suspendHistory()
  app.activeDocument.suspendHistory("Script Name", "main()");
}

function main() {
  // Common default Photoshop fonts with abbreviations
  var fontList = [
    { number: "1", abbr: "ari", name: "ArialMT" }, { number: "2", abbr: "cal", name: "Calibri" },
    { number: "3", abbr: "cmb", name: "Cambria" }, { number: "4", abbr: "cdn", name: "Candara" },
    { number: "5", abbr: "con", name: "Consolas" }, { number: "6", abbr: "cor", name: "Corbel" },
    { number: "7", abbr: "cms", name: "ComicSansMS" }, { number: "8", abbr: "crn", name: "CourierNewPSMT" },
    { number: "9", abbr: "geo", name: "Georgia" }, { number: "10", abbr: "imp", name: "Impact" },
    { number: "11", abbr: "lcn", name: "LucidaConsole" }, { number: "12", abbr: "mss", name: "MicrosoftSansSerif" },
    { number: "13", abbr: "plt", name: "PalatinoLinotype" }, { number: "14", abbr: "seg", name: "SegoeUI" },
    { number: "15", abbr: "tah", name: "Tahoma" }, { number: "16", abbr: "myp", name: "Myriad Pro" },
    { number: "17", abbr: "tnr", name: "TimesNewRomanPSMT" },
    { number: "18", abbr: "trb", name: "TrebuchetMS" }, { number: "19", abbr: "ver", name: "Verdana" }
  ];

  // Set the desired font name here (e.g., "ArialMT", "Calibri", etc.)
  var selectedFontName = "TimesNewRomanPSMT";

  // User-defined variables
  var fontName = selectedFontName;
  var textColor = new SolidColor;
  textColor.rgb.red = 255;
  textColor.rgb.green = 255;
  textColor.rgb.blue = 255;
  var minFontSize = 10; // Minimum font size in pixels
  var baseScalingFactor = 2.0; // Base scaling factor (0.01 = 1%) .1 = May force truncation

  // Additional scaling factor (modify this value as needed)
  var additionalScalingFactor = 1.0; // (1.0 = 100%) Over 100% may force truncation

  // Set the vertical offset percentage (0.0 means centered vertically, 0.25 is 25% up, -0.25 is 25% down)
  var verticalOffsetPercentage = 0.0; // Default value: 0.0 (centered vertically)

  // Set the horizontal offset percentage (0.0 means centered horizontally, 0.25 is 25% left, -0.25 is 25% right)
  var horizontalOffsetPercentage = 0.0; // Default value: 0.0 (centered horizontally)

  // Option 1: Full Path Name (Uncomment to use)
  //var fileNameWithoutExtension = decodeURI(app.activeDocument.fullName);

  // Option 2: File Name (Uncomment to use)
  var fileNameWithoutExtension = decodeURI(app.activeDocument.name.split(".")[0]);

  // Option 3: File Name with Extension (Uncomment to use)
  //var fileNameWithoutExtension = decodeURI(app.activeDocument.name);

  // Automatically adjust baseScalingFactor based on the document's resolution
  var resolutionScalingFactor = app.activeDocument.resolution / 72; // 72 PPI as the reference resolution
  baseScalingFactor = baseScalingFactor * resolutionScalingFactor;

  // If Option 1 (Full Path Name) is enabled, set the maximum baseScalingFactor to 0.05 (5%)
  if (fileNameWithoutExtension) {
    baseScalingFactor = Math.min(baseScalingFactor, 0.022);
  }

  // If Option 2 (File Name) or Option 3 (File Name with Extension) is enabled, adjust the additionalScalingFactor based on the resolution
  if (fileNameWithoutExtension) {
    var minAdditionalScalingFactor = 3.5; // Minimum additional scaling factor (0.5 = 50%) to avoid excessively small text
    var maxAdditionalScalingFactor = 6.0; // Maximum additional scaling factor (2.0 = 200%) to control text enlargement
    var resolutionScalingFactor = app.activeDocument.resolution / 72; // 72 PPI as the reference resolution
    additionalScalingFactor = Math.max(minAdditionalScalingFactor, additionalScalingFactor * resolutionScalingFactor);
    additionalScalingFactor = Math.min(maxAdditionalScalingFactor, additionalScalingFactor);
  }

  // Rest of the code...
  var invertOffset = true; // Set to true to invert the offset effect

  // Invert the vertical offset if needed
  if (invertOffset) {
    verticalOffsetPercentage *= -1;
    horizontalOffsetPercentage *= -1;
  }

  var doc = app.activeDocument;
  var docWidth = doc.width.value;
  var docHeight = doc.height.value;
  var availableWidth = docWidth - Math.abs(docWidth * horizontalOffsetPercentage); // Calculate the available width for the text based on the horizontal offset percentage
  var centerPosX = docWidth / 2 + (docWidth / 2) * horizontalOffsetPercentage; // Apply the horizontal offset
  var centerPosY = docHeight / 2 + (docHeight / 2) * verticalOffsetPercentage; // Apply the vertical offset

  // Text properties
  var fontSize = Math.max(minFontSize, availableWidth * baseScalingFactor * additionalScalingFactor); // Scale the font size based on the available width, base scaling factor, and additional scaling factor

  // Get the file name without the extension
  var textContent = fileNameWithoutExtension;

  // Save the current ruler and type
  var strtRulerUnits = app.preferences.rulerUnits;
  var strtTypeUnits = app.preferences.typeUnits;
  app.preferences.rulerUnits = Units.PIXELS;
  app.preferences.typeUnits = TypeUnits.PIXELS;

  // Resize the image to a fixed resolution (72 PPI) temporarily for consistent results
  var testRes = 72;
  var currentRes = doc.resolution;
  if (currentRes != testRes) {
    doc.resizeImage(doc.width.value, doc.height.value, testRes);
  }

  // Create a new text layer
  var textLayer = doc.artLayers.add();
  textLayer.name = doc.name;
  textLayer.kind = LayerKind.TEXT;
  textLayer.textItem.color = textColor;
  textLayer.textItem.font = fontName;
  textLayer.textItem.size = fontSize;
  textLayer.textItem.position = [centerPosX, centerPosY]; // Center-align the text with the offsets

  // Set text layer options
  textLayer.textItem.justification = Justification.CENTER; // Center-align the text horizontally
  textLayer.textItem.antiAliasMethod = AntiAlias.SHARP;

  // Set the text content
  try {
    textLayer.textItem.contents = textContent;
  } catch (error) {
    textLayer.textItem.contents = activeDocument.name;
  }

  // Restore the original resolution and preferences
  if (currentRes != testRes) {
    doc.resizeImage(doc.width.value, doc.height.value, currentRes);
  }
  app.preferences.rulerUnits = strtRulerUnits;
  app.preferences.typeUnits = strtTypeUnits;

  // Commenting out the final output for smooth operation
  /*
  var outputString = "Script executed successfully!\n\n";
  outputString += "Selected Font: " + fontName + "\n";
  outputString += "Font Size: " + fontSize + " pixels\n";
  outputString += "Text Color: RGB(" + textColor.rgb.red + ", " + textColor.rgb.green + ", " + textColor.rgb.blue + ")\n";
  outputString += "Horizontal Offset Percentage: " + (horizontalOffsetPercentage * 100) + "%\n";
  outputString += "Vertical Offset Percentage: " + (verticalOffsetPercentage * 100) + "%\n";
  outputString += "Text Content: " + textContent + "\n";

  alert(outputString, "Script Output");
  */
}

 

Participating Frequently
February 16, 2025

I'm new and know nothing about scripting or coding. This is exactly what I want to do - write the filename centered about 15% from the bottom margin. This way I can watch them on my screen saver and remember what I'm seeing.

 

I am obviously doing something wrong. I have copied, pasted, and tried each and every one of the scripts posted here. They all show something is happening in the History tab and one or more new layers show up, but I can see nothing in any of those layers, even when the rest are turned off. Yet, if I click on Type and enter text, it shows up and works normally.

 

I'm trying to work on the .psd files, because .jpgs revert back to Bridge as a raw file and end up getting converted to .psd anyway.

 

Is there some preference or switch I need to fix?

Stephen Marsh
Community Expert
February 16, 2025
quote

Is there some preference or switch I need to fix?


By @Ken287629603pzl


It's not possible for me to comment on the issues that you have had.

 

Please attach a sample PSD with a text layer with the desired font, size, position etc.

 

P.S. It might be easier for you to use alternative software for this task, where the feature is built-in and readily accessible:

 

https://www.xnview.com/en/xnconvert/

 

This example uses metadata, however, the text can also be the filename or other variables.

Jeffery Sanders
New Participant
July 29, 2023

Here it is, just as you asked for it, and then some! It's the GOLDENGUN of Photoshop name scripts; it will surely blow all others out of the water. Variables allow complete customization, and comments are plentiful for ease of editing.

Overall, the script will automatically center the filename and maximize the text size based on the limits you set, until it clips. It will also attempt to resize outputs automatically if you clip horizontally, as long as you keep reasonable values. The script offers three output options: filename, filename.extension, and path name. Additionally, you can select your font of choice from the comments, apply custom offsets from "auto center," and choose colors based on RGB values. Feel free to edit the Scaling Factors and other variables to achieve the exact output you desire, and verbose output is available as well. The variable for fonts has been improved with helpful comments, and I've added horizontal variable offsets that scale accordingly.

A special thanks to JJMack for the original script and the powerful tool, ChatGPT. Hopefully this helps someone, if you find it useful, please give me a thumbs up! If anyone wants to suggest additional features or finds any bugs, please let me know, and I will fix/add them ASAP.

 

#target photoshop // this command only works in Photoshop CS2 and higher
app.bringToFront();

if (!documents.length) {
alert('There are no documents open.', 'No Document');
} else {
// Call the main function wrapped in Document.suspendHistory()
app.activeDocument.suspendHistory("Script Name", "main()");
}

function main() {
// Common default Photoshop fonts with abbreviations
var fontList = [
{ number: "1", abbr: "ari", name: "ArialMT" }, { number: "2", abbr: "cal", name: "Calibri" },
{ number: "3", abbr: "cmb", name: "Cambria" }, { number: "4", abbr: "cdn", name: "Candara" },
{ number: "5", abbr: "con", name: "Consolas" }, { number: "6", abbr: "cor", name: "Corbel" },
{ number: "7", abbr: "cms", name: "ComicSansMS" }, { number: "8", abbr: "crn", name: "CourierNewPSMT" },
{ number: "9", abbr: "geo", name: "Georgia" }, { number: "10", abbr: "imp", name: "Impact" },
{ number: "11", abbr: "lcn", name: "LucidaConsole" }, { number: "12", abbr: "mss", name: "MicrosoftSansSerif" },
{ number: "13", abbr: "plt", name: "PalatinoLinotype" }, { number: "14", abbr: "seg", name: "SegoeUI" },
{ number: "15", abbr: "tah", name: "Tahoma" }, { number: "16", abbr: "myp", name: "Myriad Pro" },
{ number: "17", abbr: "tnr", name: "TimesNewRomanPSMT" },
{ number: "18", abbr: "trb", name: "TrebuchetMS" }, { number: "19", abbr: "ver", name: "Verdana" }
];

// Set the desired font name here (e.g., "ArialMT", "Calibri", etc.)
var selectedFontName = "TimesNewRomanPSMT";

// User-defined variables
var fontName = selectedFontName;
var textColor = new SolidColor;
textColor.rgb.red = 255;
textColor.rgb.green = 255;
textColor.rgb.blue = 255;
var minFontSize = 10; // Minimum font size in pixels
var baseScalingFactor = 2.0; // Base scaling factor (0.01 = 1%) .1 = May force truncation

// Additional scaling factor (modify this value as needed)
var additionalScalingFactor = 1.0; // (1.0 = 100%) Over 100% may force truncation

// Set the vertical offset percentage (0.0 means centered vertically, 0.25 is 25% up, -0.25 is 25% down)
var verticalOffsetPercentage = -0.80; // Default value: 0.0 (centered vertically)

// Set the horizontal offset percentage (0.0 means centered horizontally, 0.25 is 25% left, -0.25 is 25% right)
var horizontalOffsetPercentage = -.70; // Default value: 0.0 (centered horizontally)

// Option 1: Full Path Name (Uncomment to use)
var fileNameWithoutExtension = decodeURI(app.activeDocument.fullName);

// Option 2: File Name (Uncomment to use)
//var fileNameWithoutExtension = decodeURI-app.activeDocument.name.split(".")[0]);

// Option 3: File Name with Extension (Uncomment to use)
//var fileNameWithoutExtension = decodeURI(app.activeDocument.name);

// Automatically adjust baseScalingFactor based on the document's resolution
var resolutionScalingFactor = app.activeDocument.resolution / 72; // 72 PPI as the reference resolution
baseScalingFactor = baseScalingFactor * resolutionScalingFactor;

// If Option 1 (Full Path Name) is enabled, set the maximum baseScalingFactor to 0.05 (5%)
if (fileNameWithoutExtension) {
baseScalingFactor = Math.min(baseScalingFactor, 0.042);
}

// If Option 3 (File Name with Extension) is enabled, adjust the additionalScalingFactor based on the resolution
if (fileNameWithoutExtension) {
var minAdditionalScalingFactor = 1.5; // Minimum additional scaling factor (0.5 = 50%) to avoid excessively small text
var maxAdditionalScalingFactor = 6.0; // Maximum additional scaling factor (2.0 = 200%) to control text enlargement
var resolutionScalingFactor = app.activeDocument.resolution / 72; // 72 PPI as the reference resolution
additionalScalingFactor = Math.max(minAdditionalScalingFactor, additionalScalingFactor * resolutionScalingFactor);
additionalScalingFactor = Math.min(maxAdditionalScalingFactor, additionalScalingFactor);
}

// Rest of the code...
var invertOffset = true; // Set to true to invert the offset effect

// Invert the vertical offset if needed
if (invertOffset) {
verticalOffsetPercentage *= -1;
horizontalOffsetPercentage *= -1;
}

var doc = app.activeDocument;
var docWidth = doc.width.value;
var docHeight = doc.height.value;
var availableWidth = docWidth - Math.abs(docWidth * horizontalOffsetPercentage); // Calculate the available width for the text based on the horizontal offset percentage
var centerPosX = docWidth / 2 + (docWidth / 2) * horizontalOffsetPercentage; // Apply the horizontal offset
var centerPosY = docHeight / 2 + (docHeight / 2) * verticalOffsetPercentage; // Apply the vertical offset

// Text properties
var fontSize = Math.max(minFontSize, availableWidth * baseScalingFactor * additionalScalingFactor); // Scale the font size based on the available width, base scaling factor, and additional scaling factor

// Get the file name without the extension
var textContent = fileNameWithoutExtension;

// Save the current ruler and type
var strtRulerUnits = app.preferences.rulerUnits;
var strtTypeUnits = app.preferences.typeUnits;
app.preferences.rulerUnits = Units.PIXELS;
app.preferences.typeUnits = TypeUnits.PIXELS;

// Resize the image to a fixed resolution (72 PPI) temporarily for consistent results
var testRes = 72;
var currentRes = doc.resolution;
if (currentRes != testRes) {
doc.resizeImage(doc.width.value, doc.height.value, testRes);
}

// Create a new text layer
var textLayer = doc.artLayers.add();
textLayer.name = doc.name;
textLayer.kind = LayerKind.TEXT;
textLayer.textItem.color = textColor;
textLayer.textItem.font = fontName;
textLayer.textItem.size = fontSize;
textLayer.textItem.position = [centerPosX, centerPosY]; // Center-align the text with the offsets

// Set text layer options
textLayer.textItem.justification = Justification.CENTER; // Center-align the text horizontally
textLayer.textItem.antiAliasMethod = AntiAlias.SHARP;

// Set the text content
try {
textLayer.textItem.contents = textContent;
} catch (error) {
textLayer.textItem.contents = activeDocument.name;
}

// Restore the original resolution and preferences
if (currentRes != testRes) {
doc.resizeImage(doc.width.value, doc.height.value, currentRes);
}
app.preferences.rulerUnits = strtRulerUnits;
app.preferences.typeUnits = strtTypeUnits;

// Commenting out the final output
/*
var outputString = "Script executed successfully!\n\n";
outputString += "Selected Font: " + fontName + "\n";
outputString += "Font Size: " + fontSize + " pixels\n";
outputString += "Text Color: RGB(" + textColor.rgb.red + ", " + textColor.rgb.green + ", " + textColor.rgb.blue + ")\n";
outputString += "Horizontal Offset Percentage: " + (horizontalOffsetPercentage * 100) + "%\n";
outputString += "Vertical Offset Percentage: " + (verticalOffsetPercentage * 100) + "%\n";
outputString += "Text Content: " + textContent + "\n";

alert(outputString, "Script Output");
*/
}

Jeffery Sanders
New Participant
July 29, 2023

Here it is, just as you asked for it, and then some! It's the GOLDENGUN of Photoshop name scripts; it will surely blow all others out of the water. Variables allow complete customization, and comments are plentiful for ease of editing.

Overall, the script will automatically center the filename and maximize the text size based on the limits you set, until it clips. It will also attempt to resize outputs automatically if you clip horizontally, as long as you keep reasonable values. The script offers three output options: filename, filename.extension, and path name. Additionally, you can select your font of choice from the comments, apply custom offsets from "auto center," and choose colors based on RGB values. Feel free to edit the Scaling Factors and other variables to achieve the exact output you desire, and verbose output is available as well. The variable for fonts has been improved with helpful comments, and I've added horizontal variable offsets that scale accordingly.

A special thanks to JJMack for the original script and the powerful tool, ChatGPT. Hopefully this helps someone, if you find it useful, please give me a thumbs up! If anyone wants to suggest additional features or finds any bugs, please let me know, and I will fix/add them ASAP.

#target photoshop // this command only works in Photoshop CS2 and higher
app.bringToFront();

if (!documents.length) {
  alert('There are no documents open.', 'No Document');
} else {
  // Call the main function wrapped in Document.suspendHistory()
  app.activeDocument.suspendHistory("Script Name", "main()");
}

function main() {
  // Common default Photoshop fonts with abbreviations
  var fontList = [
    { number: "1", abbr: "ari", name: "ArialMT" }, { number: "2", abbr: "cal", name: "Calibri" },
    { number: "3", abbr: "cmb", name: "Cambria" }, { number: "4", abbr: "cdn", name: "Candara" },
    { number: "5", abbr: "con", name: "Consolas" }, { number: "6", abbr: "cor", name: "Corbel" },
    { number: "7", abbr: "cms", name: "ComicSansMS" }, { number: "8", abbr: "crn", name: "CourierNewPSMT" },
    { number: "9", abbr: "geo", name: "Georgia" }, { number: "10", abbr: "imp", name: "Impact" },
    { number: "11", abbr: "lcn", name: "LucidaConsole" }, { number: "12", abbr: "mss", name: "MicrosoftSansSerif" },
    { number: "13", abbr: "plt", name: "PalatinoLinotype" }, { number: "14", abbr: "seg", name: "SegoeUI" },
    { number: "15", abbr: "tah", name: "Tahoma" }, { number: "16", abbr: "myp", name: "Myriad Pro" },
    { number: "17", abbr: "tnr", name: "TimesNewRomanPSMT" },
    { number: "18", abbr: "trb", name: "TrebuchetMS" }, { number: "19", abbr: "ver", name: "Verdana" }
  ];

  // Set the desired font name here (e.g., "ArialMT", "Calibri", etc.)
  var selectedFontName = "TimesNewRomanPSMT";

  // User-defined variables
  var fontName = selectedFontName;
  var textColor = new SolidColor;
  textColor.rgb.red = 255;
  textColor.rgb.green = 255;
  textColor.rgb.blue = 255;
  var minFontSize = 10; // Minimum font size in pixels
  var baseScalingFactor = 2.0; // Base scaling factor (0.01 = 1%) .1 = May force truncation

  // Additional scaling factor (modify this value as needed)
  var additionalScalingFactor = 1.0; // (1.0 = 100%) Over 100% may force truncation

  // Set the vertical offset percentage (0.0 means centered vertically, 0.25 is 25% up, -0.25 is 25% down)
  var verticalOffsetPercentage = -0.80; // Default value: 0.0 (centered vertically)

  // Set the horizontal offset percentage (0.0 means centered horizontally, 0.25 is 25% left, -0.25 is 25% right)
  var horizontalOffsetPercentage = -.70; // Default value: 0.0 (centered horizontally)

  // Option 1: Full Path Name (Uncomment to use)
  //var fileNameWithoutExtension = decodeURI(app.activeDocument.fullName);

  // Option 2: File Name (Uncomment to use)
  var fileNameWithoutExtension = decodeURI-app.activeDocument.name.split(".")[0]);

  // Option 3: File Name with Extension (Uncomment to use)
  //var fileNameWithoutExtension = decodeURI(app.activeDocument.name);

  // Automatically adjust baseScalingFactor based on the document's resolution
  var resolutionScalingFactor = app.activeDocument.resolution / 72; // 72 PPI as the reference resolution
  baseScalingFactor = baseScalingFactor * resolutionScalingFactor;

  // If Option 1 (Full Path Name) is enabled, set the maximum baseScalingFactor to 0.05 (5%)
  if (fileNameWithoutExtension) {
    baseScalingFactor = Math.min(baseScalingFactor, 0.042);
  }

  // If Option 3 (File Name with Extension) is enabled, adjust the additionalScalingFactor based on the resolution
  if (fileNameWithoutExtension) {
    var minAdditionalScalingFactor = 1.5; // Minimum additional scaling factor (0.5 = 50%) to avoid excessively small text
    var maxAdditionalScalingFactor = 6.0; // Maximum additional scaling factor (2.0 = 200%) to control text enlargement
    var resolutionScalingFactor = app.activeDocument.resolution / 72; // 72 PPI as the reference resolution
    additionalScalingFactor = Math.max(minAdditionalScalingFactor, additionalScalingFactor * resolutionScalingFactor);
    additionalScalingFactor = Math.min(maxAdditionalScalingFactor, additionalScalingFactor);
  }

  // Rest of the code...
  var invertOffset = true; // Set to true to invert the offset effect

  // Invert the vertical offset if needed
  if (invertOffset) {
    verticalOffsetPercentage *= -1;
    horizontalOffsetPercentage *= -1;
  }

  var doc = app.activeDocument;
  var docWidth = doc.width.value;
  var docHeight = doc.height.value;
  var availableWidth = docWidth - Math.abs(docWidth * horizontalOffsetPercentage); // Calculate the available width for the text based on the horizontal offset percentage
  var centerPosX = docWidth / 2 + (docWidth / 2) * horizontalOffsetPercentage; // Apply the horizontal offset
  var centerPosY = docHeight / 2 + (docHeight / 2) * verticalOffsetPercentage; // Apply the vertical offset

  // Text properties
  var fontSize = Math.max(minFontSize, availableWidth * baseScalingFactor * additionalScalingFactor); // Scale the font size based on the available width, base scaling factor, and additional scaling factor

  // Get the file name without the extension
  var textContent = fileNameWithoutExtension;

  // Save the current ruler and type
  var strtRulerUnits = app.preferences.rulerUnits;
  var strtTypeUnits = app.preferences.typeUnits;
  app.preferences.rulerUnits = Units.PIXELS;
  app.preferences.typeUnits = TypeUnits.PIXELS;

  // Resize the image to a fixed resolution (72 PPI) temporarily for consistent results
  var testRes = 72;
  var currentRes = doc.resolution;
  if (currentRes != testRes) {
    doc.resizeImage(doc.width.value, doc.height.value, testRes);
  }

  // Create a new text layer
  var textLayer = doc.artLayers.add();
  textLayer.name = doc.name;
  textLayer.kind = LayerKind.TEXT;
  textLayer.textItem.color = textColor;
  textLayer.textItem.font = fontName;
  textLayer.textItem.size = fontSize;
  textLayer.textItem.position = [centerPosX, centerPosY]; // Center-align the text with the offsets

  // Set text layer options
  textLayer.textItem.justification = Justification.CENTER; // Center-align the text horizontally
  textLayer.textItem.antiAliasMethod = AntiAlias.SHARP;

  // Set the text content
  try {
    textLayer.textItem.contents = textContent;
  } catch (error) {
    textLayer.textItem.contents = activeDocument.name;
  }

  // Restore the original resolution and preferences
  if (currentRes != testRes) {
    doc.resizeImage(doc.width.value, doc.height.value, currentRes);
  }
  app.preferences.rulerUnits = strtRulerUnits;
  app.preferences.typeUnits = strtTypeUnits;

  // Commenting out the final output
  /*
  var outputString = "Script executed successfully!\n\n";
  outputString += "Selected Font: " + fontName + "\n";
  outputString += "Font Size: " + fontSize + " pixels\n";
  outputString += "Text Color: RGB(" + textColor.rgb.red + ", " + textColor.rgb.green + ", " + textColor.rgb.blue + ")\n";
  outputString += "Horizontal Offset Percentage: " + (horizontalOffsetPercentage * 100) + "%\n";
  outputString += "Vertical Offset Percentage: " + (verticalOffsetPercentage * 100) + "%\n";
  outputString += "Text Content: " + textContent + "\n";

  alert(outputString, "Script Output");
  */
}
rodrigounda
Known Participant
May 23, 2022

Hello people!
I've seen so many answers here, that each time I read them I know there are really capable folks here. That's really nice.

But, there is an script, or action that let a guy who doesn't know how to code . to put filename overlay over a -jpg, while adjusting the text to be centered and scaled for vert and horizontal pictures?
🙂

Brainiac
May 23, 2022

I don't know of any script specifically but you could use a watermarking utility.

In Photoshop, Plugins->Browse Plugins and look for Watermark 3.

JJMack
Community Expert
January 10, 2020

Here is a script the will add the File name the the lower left on the document if the document has been saved. If the document has not been saved it will add the Document Name to the lower left.  The script takes into consideration the document resolution and size to come up with a font size to use.  However, the script does not consider the File Path length.  Therefore, if the documents backing file path is long the text layer added may not fit on canvas. You will need to edit the text layer and change the font size.  The script can easily be change to use a larger font if you just want to ad the Document Name not the File name and path.

// This script was hacked by JJMack 
// This script is supplied as is. It is provided as freeware.
// The author accepts no liability for any problems arising from its use.
// LowerLeftFileName.jsx
// enable double-clicking from Mac Finder or Windows Explorer
#target photoshop // this command only works in Photoshop CS2 and higher
// bring application forward for double-click events
app.bringToFront();
if (!documents.length) {alert('There are no documents open.', 'No Document');} // ensure at least one document open
else { main();}

///////////////////////////////////////////////////////////////////////////////
// main - main function
///////////////////////////////////////////////////////////////////////////////
function main() {
    /* textX and TextY positions text placement 0 and 0 Top Left corner of image in pixels	*/
	var textX = 0;									
	var textY = 0;	
	/* Internal Photoshop Text name								*/								
    var fontName = "ArialMT";
	var fontName = "TimesNewRomanPSMT";
	var fontName = "Tahoma";
	/* Text Color										*/
	textColor = new SolidColor;						
	textColor.rgb.red = 255;
	textColor.rgb.green = 0;
	textColor.rgb.blue = 0;
	/* END Variables You can hard code your business owner here */

    // remember users Ruler avd Type Units and set ours
	var strtRulerUnits = app.preferences.rulerUnits;
	var strtTypeUnits = app.preferences.typeUnits;
	app.preferences.rulerUnits = Units.PIXELS;
 	app.preferences.typeUnits = TypeUnits.PIXELS;
    var testres = 72;
	res = app.activeDocument.resolution;
	if(res!=testres){ app.activeDocument.resizeImage(app.activeDocument.width.value,app.activeDocument.height.value,testres); }
	

	var docName = app.activeDocument.name;
	var doc = app.activeDocument;

	text_layer = doc.artLayers.add();						// Add a Layer
	text_layer.name = docName;							// Name Layer
	text_layer.kind = LayerKind.TEXT;						// Make Layer a Text Layer
	text_layer.textItem.color = textColor;						// set text layer color
/* Do not set TextType to Pargarph Text so action can position text layer
	text_layer.textItem.kind = TextType.PARAGRAPHTEXT;				// Set text layers text type
 */
	text_layer.textItem.font = fontName;						// set text font
	text_layer.blendMode = BlendMode.NORMAL						// blend mode
	text_layer.textItem.fauxBold = false;						// Bold
	text_layer.textItem.fauxItalic = false;						// Italic
	text_layer.textItem.underline = UnderlineType.UNDERLINEOFF;			// Underlibn
	text_layer.textItem.capitalization = TextCase.NORMAL;				// Case
	text_layer.textItem.antiAliasMethod = AntiAlias.SHARP;				// antiAlias
    if (doc.width>=1001) fontSize = 60;
	else fontSize = 10;
	text_layer.textItem.size = fontSize;						// set text font Size
	text_layer.textItem.position = Array(fontSize, (doc.height - fontSize ));	// set text layers position in and down 
/* Do not set Text Area for StampEXIF so action can position text layer
	textWidth = (doc.width - textX);						// Text width document width - offset
	textHeight = (doc.height - textY);						// Text height document height - offset
	text_layer.textItem.width = textWidth;						// set text area width
	text_layer.textItem.height = textHeight;					// set text area height
 */
	try{
        text_layer.textItem.contents = decodeURI(app.activeDocument.fullName);

	}
	catch (er) {
		text_layer.textItem.contents = activeDocument.name; 
		//alert("Error Setting Contents...");
	}
	if(res != testres){ app.activeDocument.resizeImage(app.activeDocument.width.value,app.activeDocument.height.value,res); }	
	app.preferences.rulerUnits = strtRulerUnits;
	app.preferences.typeUnits = strtTypeUnits;
}
///////////////////////////////////////////////////////////////////////////////
// END - main function
///////////////////////////////////////////////////////////////////////////////
JJMack
New Participant
March 14, 2022

Awesome Script! How would you change the script to just have the file name and not the loaction?

Brainiac
March 14, 2022

Look at the script I posted.

Brainiac
January 8, 2020

#target photoshop

testText();

function testText(){
if(documents.length > 0){
var originalDialogMode = app.displayDialogs;
app.displayDialogs = DialogModes.ERROR;
var originalRulerUnits = preferences.rulerUnits;
preferences.rulerUnits = Units.PIXELS;
try{
var docRef = activeDocument;
var LayerRef = docRef.artLayers.add();
LayerRef.kind = LayerKind.TEXT;
var TextRef = LayerRef.textItem;
var fileNameNoExtension = docRef.name;

//this section removes the file extension
fileNameNoExtension = fileNameNoExtension.split('.');
if(fileNameNoExtension.length > 1){
fileNameNoExtension.length--;
}
fileNameNoExtension = fileNameNoExtension.join('.');
//

TextRef.contents = fileNameNoExtension;

//this section positions the text and sets text parameters
TextRef.position = new Array(0, 0);
preferences.rulerUnits = Units.POINTS;
TextRef.size = 96;
TextRef.useAutoLeading = false;
TextRef.leading = 42;
TextRef.font = 'Calibri-Bold';
TextRef.justification = Justification.CENTER;
TextRef.autoKerning = AutoKernType.METRICS;
//

}
catch(e){
preferences.rulerUnits = originalRulerUnits;
app.displayDialogs = originalDialogMode;
return;
}
preferences.rulerUnits = originalRulerUnits;
app.displayDialogs = originalDialogMode;
}
else{
alert('You must have a document open to run this script.');
return;
}
}

JJMack
Community Expert
January 8, 2020

Text is complicated and your docRef.name is not a file name. Photoshop is a document editor and that would bet the Document name.  I opened a new document 300px by 200px 300ppi. Its new document so there is no file on disk  it has not been saved. I ran your script. It added a text layer Untitled-1. A huge text layer that was mostly off canvas and much larger than canvas.  Text is complex. You can not use size 96 for all documents

Here is a 300px by ]200px 300ppi image my stampexif script had no problem adding a text layer that had a good size for the document.

 I had a heck of a time  I added some comment in my script in cast a needed to set a size in  a future script  I could reference.

 

/* Trying to figure out font size for the number of lines to cover the document height */
/* and getting setting text area to cover the document was a trip. Adobe Postscript trip */
/* I believe that 72 or 72.27 Point/Pica Size Photoshop Preference maybe I should see if */
/* I could retrieve it. Anyway mine is set to 72 Setting the document resolution taking */
/* the document width and dividing by 72 would probably yield number of characters that */
/* would fit in the document width. Setting the documents resolution comes into play */
/* with Photoshop text support. Using the documents height and dividing the by the number */
/* of lines of text I needed I hoped would yield the font size I needed. However that */
/* did not work the text area was correct the number of text lines did not fit. I needed */
/* to use a smaller font. When the document resolution is set to 72 DPI and I set a text */
/* layer font size to 72 and the text area the number of pixels I want and observing */
/* Photoshop's text options bar there I see a one 1 to one relationship. 72 px = 72 px. */
/* If I set the documents resolution lower and set a Photoshop text layer font size to */
/* 72 px I see Photoshop scale the number to a lower number of pixels in the option bar. */
/* Just what I needed. Setting the Documents resolution to 60 DPI let the number of line */
/* I needed fit on the document. However Photoshop also scaled the text area I set down */
/* in size and that number of lines did not fit within that area. I needed to scale the */
/* text area up. Scaling the Text area up using 72/resolution did the trick... */

 

I can not remember why I use 30 in my size calc and what other width and height figures I played with,  The script saved the document resolution and changed the resolution to 60ppi added the text layer then restored the document to its original resolution. I knew nothing about scripting back then was one if my first scripts for actions.  I knew a lot about actions and created some hacks for use actions. The stamp was positioned and layer styled by the action that used stampexif script to add the text layer.

 

var testres = 60;
res = app.activeDocument.resolution;
if(res!=testres){ app.activeDocument.resizeImage(app.activeDocument.width.value,app.activeDocument.height.value,testres); }

 

/* Calulate font size to use for StampExit keep size same for landscape and portrait base on document size */
if (doc.width >= doc.height) {var fontSize = Math.round(doc.height / (30 * sizeFactor));}
else {var fontSize = Math.round(doc.width / (30 * sizeFactor));}
if (fontSize<10){fontSize=10}; // don't use Font size smaller then 10

text_layer.textItem.size = fontSize; // set text font Size

 

 

Resolution restore

 

if(res != testres){ app.activeDocument.resizeImage(app.activeDocument.width.value,app.activeDocument.height.value,res); }

 

JJMack
Brainiac
January 9, 2020

Its not complicated, its a working script that I use in production. I've run this script on more than 14,000 files to add the filename to the image.

The coordinates have to be changed to put the text where the user wants. 96 points is what I use for images, obviously those values (and things like the font) are determined by the user.

Just because you don't understand it doesn't mean its not a production script.

Myra Ferguson
Community Expert
January 8, 2020

You actually don't need a script if your image is on an artboard. There are a couple of ways to add the name. I'm assuming you mean you want the name to show up as part of the image. Name the artboard with the name that you want to appear in the upper left. Go to File > Export > Artboards to Files..., select the File Type:  PSD, and in the options make sure Include Artboard Name is selected. Below the options is another set of options for the font and the extension of the canvas. If you just want the name to appear when you're working on the file but not be a part of the file, you could name your artboard and go to View > Show > Artboard Names. Be aware that if you have the View set to show the artboard name and you export the artboard as a PSD with Include Artboard Name selected, the name will appear twice in the upper left of the image.

JJMack
Community Expert
January 8, 2020

Add a text Layer containing the active document's  the backing file path and align the layer to the document's top right corner.  You need a script to get the Backing File path then add the text layer.  The layer can easily be position by an action that does a select all then align the active layer the layer add by the script to the selection top right. You need to know the font you want to use and use a text size the is appropriate for the docyment's size and resolution.  If you do not know JavaScript and Photoshop DOM it will be quite a challenge for you.  Getting the Backing File path is is easy adding  a text layer is easy  Setting and appropriate text size is not that easy. There are a lot of settings for a text layer location, font, size, color, attributes like italic etc. Also file name encoding and defaults and constructs like ~ could be "C:\Users\your user Id"  on Windows Perhaps something else on a Mac.   You may want to convert the file name toe the system file form  like ~/path/name.ext  you would change to C:\users\userid\path\name.ext on a windows system.

 

alert(activeDocument.fullName);
text_layer = activeDocument.artLayers.add(); // Add a Layer
text_layer.kind = LayerKind.TEXT; // Make Layer a Text Layer
text_layer.textItem.contents = decodeURI(app.activeDocument.fullName);

JJMack
Participating Frequently
July 29, 2020

I am using this script to add filename as a layer. How to I get it to leave off the last chacter of file

example my file is called L10100-1A and want the added layer filename to be L1100-1

 

 

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!" );
}

JJMack
Community Expert
July 29, 2020