I am starting out in photoshop with a .tif file. I run a script which adds some layers etc and then i save the file as a .psd in a new folder.
The problem i am having is checking to see if a .psd file already exists with the same name. My goal is to simply close down the .tif file without saving if a .psd with the same name appears in the folder.
Here is my save code:
//Save document
var savePath = Folder(doc.path.parent) + "/new_folder/";
saveFile = new File(savePath);
saveOptions = new PhotoshopSaveOptions;
saveOptions.embedColorProfile = true;
if ( WHAT SHOULD I BE ASKING HERE? ) {
doc.saveAs(saveFile, saveOptions, false, Extension.LOWERCASE);
} else {
doc.close(SaveOptions.DONOTSAVECHANGES);
}
I'm stuck with what add to the if function? I've tried .exists but it's not working because the current file is still in .tif mode and hasn't saved to .psd yet. So it just keeps on saving and overwriting the previous saved .psd
Any help would be most welcome. :)
EDIT:
Thought i had it working with this but still no luck:
//Strip .tif and add .psd to file name
var docName = doc.name;
PSDName = docName.substr(0,docName.length-3);
PSDName = PSDName + "psd";
//Save document
var savePath = Folder(doc.path.parent) + "/new_folder/";
saveFile = new File(savePath);
saveOptions = new PhotoshopSaveOptions;
saveOptions.embedColorProfile = true;
var savedFile = savePath + "/" + PSDName
if (! savedFile.exists ) {
doc.saveAs(saveFile, saveOptions, false, Extension.LOWERCASE);
} else {
doc.close(SaveOptions.DONOTSAVECHANGES);
}
the if statement is returning false every time and the doc is not saving. If i take away the ! it saves every time.
Make a new variable with the filename that you want to test - i.e. the name of the .PSD file and use that. For example, strip off the TIF and replace it with PSD then use .exists.
var ImageName = activeDocument.name;
PSDName = ImageName.substr(0,ImageName.length-3); // Strip "TIF" from end
PSDName = PSDName + "psd"; // Add on "PSD" instead
If you need to debug your script, you can do something like this:
// Change Debug=1 for extra debugging messages, Debug=0 for no messages
var Debug=1;
...
if(Debug)alert(PSDName);
...
if(Debug)alert("File exists");
Related
I have a javascript I found but it starts with having the user choose a folder where it will grab files. I want to create a watch folder so I want to tell the javascript the folder to grab the files from, not let the user choose. I can't for the life of me figure out how to do this. I know applescript but cannot grasp javascript. Thank you!
Here is what I believe the area I need to change:
function main() {
// user settings
var prefs = new Object();
prefs.sourceFolder = '/Volumes/SERVER_RAID/•Current/MPC'; // default browse location (default: '~')
prefs.removeFileExtensions = true; // remove filename extensions for imported layers (default: true)
prefs.savePrompt = true; // display save prompt after import is complete (default: false)
prefs.closeAfterSave = true; // close import document after saving (default: false)
// prompt for source folder
var sourceFolder = Folder.selectDialog('Where are the Front and Back files?', Folder(prefs.sourceFolder));
// ensure the source folder is valid
if (!sourceFolder) {
return;
}
else if (!sourceFolder.exists) {
alert('Source folder not found.', 'Script Stopped', true);
return;
}
// add source folder to user settings
prefs.sourceFolder = sourceFolder;
// get a list of files
var fileArray = getFiles(prefs.sourceFolder);
// if files were found, proceed with import
if (fileArray.length) {
importFolderAsLayers(fileArray, prefs);
}
// otherwise, diplay message
else {
alert("The selected folder doesn't contain any recognized images.", 'No Files Found', false);
}
}
///////////////////////////////////////////////////////////////////////////////
// getFiles - get all files within the specified source
///////////////////////////////////////////////////////////////////////////////
function getFiles(sourceFolder) {
// declare local variables
var fileArray = new Array();
var extRE = /\.(?:png)$/i;
// get all files in source folder
var docs = sourceFolder.getFiles();
var len = docs.length;
for (var i = 0; i < len; i++) {
var doc = docs[i];
// only match files (not folders)
if (doc instanceof File) {
// store all recognized files into an array
var docName = doc.name;
if (docName.match(extRE)) {
fileArray.push(doc);
}
}
}
// return file array
return fileArray;
}
///////////////////////////////////////////////////////////////////////////////
To achieve this you'll need to specify the path to your desired folder as String.
If you take a look at the updated code sample below you'll notice that line 4 of your original code which read:
prefs.sourceFolder = '/Volumes/SERVER_RAID/•Current/MPC';
has been changed to:
prefs.sourceFolder = Folder('~/Desktop/targetFolder');
This now assumes the target folder is named targetFolder and it resides in your Desktop folder. You'll need to change the '~/Desktop/targetFolder' part as necessary to point to the folder you actually want. It also assumes you're running this on macOS as the shortcut to the Desktop folder (i.e. the ~/ part) will not be recognized on Windows.
What are the other ways I can specify the path?
You can specify path name using absolute paths such as:
prefs.sourceFolder = Folder('/Users/JohnDoe/Desktop/targetFolder');
Note: This example actually points to the same folder as the first example. Assuming that the user is called John Doe of course!
More info about setting file paths can be found here.
What other changes were made to your code example:
Lines 9 to 22 in your example code which read:
// prompt for source folder
var sourceFolder = Folder.selectDialog('Where are the Front and Back files?', Folder(prefs.sourceFolder));
// ensure the source folder is valid
if (!sourceFolder) {
return;
}
else if (!sourceFolder.exists) {
alert('Source folder not found.', 'Script Stopped', true);
return;
}
// add source folder to user settings
prefs.sourceFolder = sourceFolder;
are now redundant. Instead, they have been replaced with the following snippet which will alert you if the folder you specified cannot be found:
// ensure the source folder exists.
if (!prefs.sourceFolder.exists) {
alert('Source folder not found.\n' + prefs.sourceFolder, 'Script Stopped', true);
return;
}
I added main() on line 30 below to invoke the main function. However, if you have that elsewhere in your code you can delete it.
Updated code sample:
function main() {
// User settings
var prefs = new Object();
prefs.sourceFolder = Folder('~/Desktop/targetFolder');
prefs.removeFileExtensions = true;
prefs.savePrompt = true;
prefs.closeAfterSave = true;
// ensure the source folder exists.
if (!prefs.sourceFolder.exists) {
alert('Source folder not found.\n' + prefs.sourceFolder, 'Script Stopped', true);
return;
}
// Get a list of files
var fileArray = getFiles(prefs.sourceFolder);
// If files were found, proceed with your tasks.
if (fileArray.length) {
alert('I found image(s) in the specified folder\n' +
'Now you need to write code to perform out a task :)');
// <-- Continiue your code here
}
// otherwise, diplay message
else {
alert('The selected folder doesn\'t contain any recognized images.', 'No Files Found', false);
}
}
main(); // <-- Invokes the `main` function
/**
* getFiles - get all files within the specified source
* #param {String} sourceFolder - the path to the source folder.
*/
function getFiles(sourceFolder) {
// declare local variables
var fileArray = new Array();
var extRE = /\.(?:png)$/i;
// get all files in source folder
var docs = sourceFolder.getFiles();
var len = docs.length;
for (var i = 0; i < len; i++) {
var doc = docs[i];
// only match files (not folders)
if (doc instanceof File) {
// store all recognized files into an array
var docName = doc.name;
if (docName.match(extRE)) {
fileArray.push(doc);
}
}
}
// return file array
return fileArray;
}
I'm trying to save the activeDocument as a .psd but its returning this error
ERROR: General Photoshop error occurred. This functionality may not be available in this version of Photoshop.
my script:
#target photoshop
var fileRef = new File(app.path.toString() + "/Samples/template.psd");
var docRef = open(fileRef);
//target text layer
var layerRef = app.activeDocument.layers.getByName("Text");
//user input
var newText = prompt("Editing " + layerRef.name, "enter new text: ");
//change contents
layerRef.textItem.contents = newText;
//save
var savePath = "/Samples/" + newText + ".psd";
var saveFile = new File(savePath);
var saveOptions = new PhotoshopSaveOptions();
saveOptions.alphaChannels = false;
saveOptions.annotations = false;
saveOptions.embedColorProfile = true;
saveOptions.layers = true;
saveOptions.spotColors = false;
app.activeDocument.saveAs(saveFile, saveOptions, true, Extension.LOWERCASE);
app.activeDocument.close();
what I want to do is basically, duplicate a template file over and over, only replacing the contents of a text layer then saving it under the string I replace in the text layer.
any tips or help is greatly appreciated.
Resolved
I fixed my problem, by a work around. I moved both the script and the template file into the Photoshop directory and added app.path.toString() to the saveFile output variable. So it seems that the path needed to be converted to a string before saving.
As of yet I am unsure how to work outside the Photoshop directory but for me this works so I'm happy. It's a fairly crude but I'm open to suggestion. So if anyone is having a similar issue they can use this for reference.
#target photoshop
var loop = true;
var filePath = "/Samples/template.psd";
while(loop) {
openTemplate(filePath);
var layerRef = app.activeDocument.layers.getByName("Text"); //target text layer
var newText = prompt("Editing " + layerRef.name, "enter new text: "); //user input
if(newText == "stop") { //stop loop by entering 'stop'
loop = false;
}
layerRef.textItem.contents = newText;
var savePath = app.path.toString() + "/Samples/" + newText + ".psd";
var saveFile = new File(savePath);
savePSD(saveFile);
app.activeDocument.close(SaveOptions.DONOTSAVECHANGES);
}
function openTemplate(filePath) { //open template.psd
var fileRef = new File(app.path.toString() + filePath);
var docRef = open(fileRef);
}
function savePSD(saveFile) { //saveas newText.psd
var saveOptions = new PhotoshopSaveOptions();
saveOptions.alphaChannels = false;
saveOptions.annotations = false;
saveOptions.embedColorProfile = true;
saveOptions.layers = true;
saveOptions.spotColors = false;
app.activeDocument.saveAs(saveFile, saveOptions, true, Extension.LOWERCASE);
}
I suspect the problem with your original attempt is that you are not specifying a full path. I always provide a full path - even if it is just to a temporary location like '/c/temp/myfile.psd'.
app.path returns a File object, not a string. In your case, you most likely want the platform-specific fullpath string:
var appPath = app.path.fsName; // "C:\Program Files\Adobe\Adobe Photoshop 2022"
Regardless if paths are correct, if you're attempting to save anything to a directory located inside the Photoshop installation directory, you will probably need to run Photoshop as administrator.
below is my test directory structure:
I have made a script which works on a psd file in the finals folder. My aim is to save it to the tifs folder. This is the code i have:
app.activeDocument.saveAs(file."../tifs", TiffSaveOptions, true, Extension.LOWERCASE);
I am well and truly stuck. I have tried so many combinations and everything is throwing an error. I just want to come out of the finals folder, and then go into the tifs folder and save.
any help would be much appreciated. :)
You've not set up your file path correctly. I suspect "../tifs" isn't working as you'd hoped. Here it is in full.
// Flatten the tiff
app.activeDocument.flatten();
// set up the new directory
// make sure you change this or
// have a folder in c:\testpsd\tifs
var myFolder = "c:\\testpsd\\tifs"; // add extra escape slash
// get the documents name
var myFileName = app.activeDocument.name;
// remove it's extension
var myDocName = myFileName.substring(0,myFileName.length -4);
// set the new filename and path
var myFilePath = myFolder + "/" + myDocName + ".tiff";
// tiff file options
var tiffFile = new File(myFilePath);
tiffSaveOptions = new TiffSaveOptions();
tiffSaveOptions.byteOrder = ByteOrder.MACOS;
tiffSaveOptions.layers = false;
tiffSaveOptions.transparency = true;
tiffSaveOptions.alphaChannels = true;
tiffSaveOptions.embedColorProfile = false;
tiffSaveOptions.imageCompression = TIFFEncoding.TIFFLZW;
tiffSaveOptions.saveImagePyramid = false;
// finally save out the document
activeDocument.saveAs(tiffFile, tiffSaveOptions, false, Extension.LOWERCASE);
I'm trying to save a file in Illustrator using Javascript but I keep getting an error.
Here is what works, but is not what I want:
// save as
var dest = "~/testme.pdf";
saveFileToPDF(dest);
function saveFileToPDF (dest) {
var doc = app.activeDocument;
if ( app.documents.length > 0 ) {
var saveName = new File ( dest );
saveOpts = new PDFSaveOptions();
saveOpts.compatibility = PDFCompatibility.ACROBAT5;
saveOpts.generateThumbnails = true;
saveOpts.preserveEditability = true;
alert(saveName);
doc.saveAs( saveName, saveOpts );
}
}
The var "dest" saves the file to the root of my Mac user account. I simply want to save the file relative to the source document in a subfolder, so I tried this:
var dest = "exports/testme.pdf";
This brings up a dialogue with ".pdf" highlighted, properly awaiting input inside the "exports" folder that I already created. I can type something and it will save, but it ignores the file name "testme.pdf" that was specified in the code. I can type "cheese" over the highlighted ".pdf" it knows I want, and it will save "cheese.pdf" in the folder "exports".
I also tried these with no luck:
var dest = "exports/testme";
var dest = "/exports/testme.pdf";
var dest = "testme.pdf";
etc., etc.
What am I missing?
To use saveAs without a dialog popping up, you need to use the global property userInteractionLevel:
var originalInteractionLevel = userInteractionLevel;
userInteractionLevel = UserInteractionLevel.DONTDISPLAYALERTS;
...
userInteractionLevel = originalInteractionLevel;
Since you want to save relative to your document, so first find the path for your current document as follows
var path = app.activeDocument.path;
var dest = path + "/exports/testme.pdf";
You can also check whether exports folder exists or not if not you can create with script as follows
var path = app.activeDocument.path;
var exportFolder = Folder(path + "/exports");
if(!exportFolder.exists){
exportFolder.create();
}
var dest = exportFolder + "/testme.pdf";
I have the following JS function which serves as a first prototype for a mozilla thunderbird extension.
The goal is to connect to a server and download a sample file, then unzipping it and storing the contents in the thunderbird profile folder.
Now this all works fine, except that the execution of the function stops after creating the zip file on the file system. So i have to restart the function again, in order to get the second part of the function executed which extracts the user.js file from the zip file.
Any ideas what the problem could be?
function downloadFile(httpLoc) {
// get profile directory
var file = Components.classes["#mozilla.org/file/directory_service;1"].
getService(Components.interfaces.nsIProperties).
get("ProfD", Components.interfaces.nsIFile);
var profilePath = file.path;
// change profile directory to native style
profilePath = profilePath.replace(/\\/gi , "\\\\");
profilePath = profilePath.toLowerCase();
// download the zip file
try {
//new obj_URI object
var obj_URI = Components.classes["#mozilla.org/network/io-service;1"].getService(Components.interfaces.nsIIOService).newURI(httpLoc, null, null);
//new file object
var obj_TargetFile = Components.classes["#mozilla.org/file/local;1"].createInstance(Components.interfaces.nsILocalFile);
//set to download the zip file into the profil direct
obj_TargetFile.initWithPath(profilePath + "\/" + "test.zip");
//if file the zip file doesn't exist, create it
if(!obj_TargetFile.exists()) {
alert("zip file wird erstellt");
obj_TargetFile.create(0x00,0644);
}
//new persitence object
var obj_Persist = Components.classes["#mozilla.org/embedding/browser/nsWebBrowserPersist;1"].createInstance(Components.interfaces.nsIWebBrowserPersist);
// with persist flags if desired ??
const nsIWBP = Components.interfaces.nsIWebBrowserPersist;
const flags = nsIWBP.PERSIST_FLAGS_REPLACE_EXISTING_FILES;
obj_Persist.persistFlags = flags | nsIWBP.PERSIST_FLAGS_FROM_CACHE;
//save file to target
obj_Persist.saveURI(obj_URI,null,null,null,null,obj_TargetFile);
} catch (e) {
alert(e);
} finally {
// unzip the user.js file to the profile direc
// creat a zipReader, open the zip file
var zipReader = Components.classes["#mozilla.org/libjar/zip-reader;1"]
.createInstance(Components.interfaces.nsIZipReader);
zipReader.open(obj_TargetFile);
//new file object, thats where the user.js will be extracted
var obj_UnzipTarget = Components.classes["#mozilla.org/file/local;1"].createInstance(Components.interfaces.nsILocalFile);
//set path for the user.js
obj_UnzipTarget.initWithPath(profilePath + "\/" + "user.js");
// if user.js doesn't exist, create it
if(!obj_UnzipTarget.exists()) {
alert("user.js wird erstellt");
obj_UnzipTarget.create(0x00,0644);
}
// extract the user.js out of the zip file, to the specified path
zipReader.extract("user.js", obj_UnzipTarget);
zipReader.close();
}
}
var hello = {
click: function() {
downloadFile("http://pse2.iam.unibe.ch/profiles/profile.zip");
},
};
saveURI is asynchronous, so you need to set the progress listener on the persist object to know when it has finished. Here's an example of setting a progress listener and later on there's a check to see whether the transfer has finished.