Illustrator edit link filepath via javascript - javascript

Edit, original copy marked below:
I've managed to create a semi-functioning script. I realized, to much frustration, that the syntax errors were the '' marks of text edit. It semi-works in that it will relink some files and usually ends in an error, "placedArt does not exist" after a few loops through. I feel like the XML finds more "stRef:filePath"s than exist in the file. Example: file with two images finds a file path for each twice. Any tips?
var counter = 0;
var doc = app.activeDocument;
var x = new XML(doc.XMPString);
var m = x.xpath('//stRef:filePath');
if (m !== '') {
for (var i=0, len=m.length(); i < len ; i++) {
var link_path = m[i];
if ( File(link_path).exists === false ) {
link_path = link_path.split('/Projects').join('/Volumes/Projects')
link_path = link_path.split('O:').join('/Volumes/Projects');
link_path = link_path.split('P:').join('/Volumes/Projects');
link_path = link_path.split('\\SERVER').join('Volumes');
link_path = link_path.split("\\").join("/");
if ( File(link_path).exists === true ){
placedArt = app.activeDocument.placedItems[i];
placedArt.relink(new File (link_path));}
alert(File(link_path).fsName);
counter++;
}
};}
if ( counter > 0 ) {
alert("Attempted to relink " + counter + " links");}
else {
alert("No links replaced");}
orginal post
Okay, I'm very inexperienced XML, but I'm trying to edit parts of a link filepath in Adobe Illustrator using a script. Below is what I have so far:
var doc = app.activeDocument;
var x = new XML(doc.XMPString);
var m = x.xpath('//stRef:filePath');
if (m !== '') {
for (var i=0, len=m.length(); i < len ; i++) {
var link_path = m[i];
if ( File(link_path).exists === false ) {
var link_path2 = String(link_path)
link_path2 = link_path2.replace(‘%5C’, ‘/‘)
alert(File(link_path2));
}
};
}
This returns an error:8 syntax error. on the line link_path2 = link_path2.replace(‘%5C’, ‘/‘). So does any attempt to redefine link_path2, such as
link_path2 = 'cow';
I currently am changing, the link_path to link_path2 to convert it into a string, assuming that the fact that the var link_path returns typeof XML is an issue for redefining, or editing the value.
The end goal is to edit the filepath from a windows server path to a macOS filepath, to script fix broken links. I've searched for hours on this, and keep hitting dead ends.

I don't if XML/XMP data is the best way to do this. We had a similar issue with linked files at our firm in swapping linked images from one server to another. This opens each AI file, looks for placed items and relinks the images to the new path. I have only used this on a PC, so I am not sure if this will work without the Mac path being available, but figured you could try.
Are you always using the same two file paths, or would you like to select them uniquely each time? If you have a two set server paths that you just want to swap, you can use something like this (I have a similar one where you pick the initial location and the destination for the files):
// Select the source folder.
var destFolder, sourceFolder, files, fileType, doc, targetFile, pngExportOpts;
if (app.documents.length == 0 ){
sourceFolder = Folder.selectDialog( 'Select the folder with Illustrator files you want to relink', '~' );
// If a valid folder is selected
if ( sourceFolder != null ){
files = new Array();
// Get all files matching the filetype
files = sourceFolder.getFiles("*.ai");
if ( files.length > 0 ) {
for ( i = 0; i < files.length; i++ ){
doc = app.open(files[i]); // returns the document object
changeExt();
if (app.documents.length != 0){
doc.save();
doc.close();
}
}
}
}
}
else{
changeExt();
}
function changeExt(){
var i;
var doc = app.activeDocument;
if (doc.placedItems.length != 0){
for (i=0;i<doc.placedItems.length;i++) {
//gets the full path of the image
var imageName = doc.placedItems[i].file.fsName;
var imageURL = doc.placedItems[i].uRL;
var imagePath;
var newPath;
var i, in_file, out_file;
//if the scan is placed for the first time it uses the drive letter
//this swaps the drive letters to the server names so they can be replaced properly
if (imageName.match(/O:/)){
imagePath = imageName.replace("O:", "\\\\Serv01\\Projects1")
imageName = imagePath;
}
else (imageName.match(/P:/)){
imagePath = imageName.replace("P:", "\\\\Serv02\\Projects2")
imageName = imagePath;
}
if (imageName.match(/Serv02/)){
imagePath = imageName.replace("Serv02", "Serv01")
activePath = imagePath.replace("Projects2", "Projects1");
newPath = File(activePath);
if (newPath.exists){//copies scan over if it doesn't exist.
doc.placedItems[i].file = newPath;
}
else{
in_file = doc.placedItems[i].file;
out_file = File(activePath);
in_file.copy(out_file);
doc.placedItems[i].file = out_file;
}
}
else{
imagePath = imageName.replace("Serv01", "Serv02")
activePath = imagePath.replace("Projects1", "Projects2");
newPath = File(activePath);
if (newPath.exists){//copies scan over if it doesn't exist.
doc.placedItems[i].file = newPath;
}
else{
in_file = doc.placedItems[i].file;
out_file = File(activePath);
in_file.copy(out_file);
doc.placedItems[i].file = out_file;
}
}
}
}
else{
doc.close(SaveOptions.DONOTSAVECHANGES);
}
}

If that is the case and the starting point and ending point are different, we used a script like this for transferring files with links from one location to another, and allows you to pick the starting location and the destination. Again, can't promise it will work for a Mac, but maybe some of this can help you. In our setup we store graphics in one folder and scans in another, so you may need to adjust the file paths if you keep it all in one folder. So we have a root folder and within that folder a "Graphics" folder and a "Scans" folder.
This also has a try/catch for files missing scans and will spit them out in an error list at the end so you know which files have missing images.
Hope some of this helps!
// Select the source folder.
sourceFolder = Folder.selectDialog( 'Select the GRAPHICS folder with Illustrator files you want to move', '~' );
var export_folderSelect = Folder.selectDialog("Select the root folder (NOT GRAPHICS) to move the Illustrator files to");
var export_folder = export_folderSelect + "/Graphics";
var errorList = [];
var destFolder, sourceFolder, files, fileType, doc, targetFile, pngExportOpts;
var save_options = new IllustratorSaveOptions();
save_options.embedICCProfile = true;
save_options.pdfCompatible = true;
// If a valid folder is selected
if ( sourceFolder != null && export_folderSelect != null){
files = new Array();
// Get all files matching the pattern
files = sourceFolder.getFiles("*.ai");
if ( files.length > 0 ){
// Get the destination to save the files
app.userInteractionLevel = UserInteractionLevel.DONTDISPLAYALERTS;
for ( i = 0; i < files.length; i++ ){
//try to open the file and move it over, otherwise note it in the error list.
var docOpened = true;
try{
doc = app.open(files[i]); // returns the document object
}
catch(e){
errorList.push(files[i].name + " !!!CORRUPT - NOT COPIED!!!");
docOpened = false;
}
try{
moveFile();
}
catch(e){
if (docOpened == true){
doc.close();
}
}
}
}
if (errorList.length > 0){
alert("COPY THIS LIST TO WORD: " + errorList);
}
else{
alert("Woo hoo! No errors!");
}
app.userInteractionLevel = UserInteractionLevel.DISPLAYALERTS;
}
function moveFile(){
const FILE_SUFFIX = "";
const ASSET_SUFFIX = "";
var doc = app.activeDocument;
if (!doc.saved) doc.save();
var original_file = doc.fullName;
var extension = "";
var arr = doc.name.split(".");
if (arr.length>1) extension = "." + arr.pop();
var filename = arr.join(".");
var assets_folder = new Folder(export_folderSelect + "/Scans");
if (assets_folder.exists || assets_folder.create()) {
var f, in_file, out_file;
for (f=0;f<doc.placedItems.length;f++) {
try{
in_file = doc.placedItems[f].file;
out_file = File(assets_folder+"/"+in_file.name);
in_file.copy(out_file);
doc.placedItems[f].file = out_file;
}
catch(e){
errorList.push(files[i].name + " SCAN MISSING");
}
}
for (g=0;g<doc.rasterItems.length;g++) {
if (doc.rasterItems[g].embedded == false) {
try{
in_file = doc.rasterItems[g].file;
out_file = File(assets_folder+"/"+in_file.name);
in_file.copy(out_file);
doc.rasterItems[g].file = out_file;
}
catch(e){
errorList.push(files[i].name + " SCAN MISSING");
}
}
}
// save as new file
packaged_file = File(export_folder + "/" + filename + FILE_SUFFIX + extension);
doc.saveAs(packaged_file, save_options);
doc.close();
// re-open the original file
//app.open(File(original_file));
} else {
alert("Unable to create the assets folder.");
}
}

This doesn't answer your question directly but it may solve your problem or be helpful to others.
There is a totally different solution.
Illustrator always looks for missing artwork in a "Links" folder in the same folder as the document.
If you regularly need to move projects around, just keep the artwork in a "Links" folder with the AI file and you can open the AI file anywhere without breaking the links.

Why are using XMP Data for this? You can get all placedItems placed in the document and you can check whether links exist or not and if not exists you relink them to the new file. Here is the small script for this
var activeDocument = app.activeDocument;
var links = activeDocument.placedItems;
for (var i = 0; i < links.length; i++) {
try {
var file = links[i].file;
if (file && file.exists) {
// Do anything as oer your requirement if link exists.
}
} catch (e) {
// if link missing relink with new_File
links[i].relink(File(new_File));
}
}
When you relink links for missing links, it will automatically update in document XMP.

Related

Bridgetalk - adobe scripting saving with variables, proper quoting, replace string with variable in string script

I'm having an issue with saving a file and I can't tell why it's not working. This is original code. I believe I'm commenting out the variables incorrectly or adobe syntax is incorrect. Does anyone have experience with this? (part that is broken: ,app.activeDocument.saveAs(File('"+psdpath+"'/' + doc.name.replace('PLACEHOLDER', '"+parentdirectory+"'))";). Quote variations are important otherwise it doesn't properly send to illustrator.
Full script:
#target photoshop
//run action in photoshop
app.doAction ("action name", "action set name");
//get path of the open document
var psdpath = activeDocument.path.fsName;
//get directory name of psd, to use in filename later
var parentdirectory = activeDocument.path.name;
//start bridgetalk
var bt = new BridgeTalk;
//targets version 25. v26 crashes if window isnt active at run
bt.target = "illustrator-25";
//run action in illustrator (which opens an eps w/linked file and performs certain tasks) and then save the document
var script = "app.doScript('action name', 'action set name'),app.activeDocument.saveAs(File('"+psdpath+"'/' + doc.name.replace('PLACEHOLDER', '"+parentdirectory+"'))";
//the entire action must be within double quotes
// var script = alert("test", "this sends alert to photoshop");
// var script = "alert('test', 'this sends alert to illustrator'),alert('"+psdpath+"', '"+psdpath+"')"; //psdpath is properly sent to illustrator
bt.body = script;
bt.send();
UPDATE 03/03/2022
Partially working (string replace does not work):
#target photoshop
var psdpath = activeDocument.path.fsName;
var parentdirectory = activeDocument.path.name;
app.doAction ("Photoshop Action Name", "Photoshop action Set");
var strScript = """
app.doScript("Illustrator Action Name", "Illustrator Action Set");
var doc = app.activeDocument;
if (documents.length > 0){
var saveOpts = new EPSSaveOptions();
saveOpts.embedLinkedFiles = embedImage = false;
saveOpts.embedAllFonts = embedFont = true;
saveOpts.includeDocumentThumbnails = false;
saveOpts.saveMultipleArtboards = false;
fullDocName = doc.fullName;
for (i=0; i<doc.layers.length; i++){
if (i-1<0) doc.layers[i].visible = true;
else {
doc.layers[i-1].visible = false;
doc.layers[i].visible = true;
}
if (doc.layers[i].locked == false) {
docName = doc.layers[i].name+".eps";
var saveName = new File ( psdpathh + "/" + parentdirectoryy + ".eps");
doc.saveAs( saveName, saveOpts );
}
}
}
""";
var editedScript = strScript.replace("psdpathh", psdpath);
var editedScript2 = editedScript.replace("parentdirectoryy", parentdirectory);
BridgeTalk.bringToFront("illustrator");
var bt = new BridgeTalk;
bt.target = "illustrator-25";
bt.body = editedScript2;
bt.send();
As a guess.
Perhaps here ...'action set name'),app.activeDocument... should be ; instead of ,:
var script = "app.doScript('action name', 'action set name'); app.activeDocument.saveAs(File('"+psdpath+"'/' + doc.name.replace('PLACEHOLDER', '"+parentdirectory+"'))";
#target photoshop
app.doAction ("ps action name", "ps action set"); //replace w your action details
var psdpath = activeDocument.path.fsName;
var parentdirectory = activeDocument.path.name;
var strScript = """
app.doScript("illustrator action name", "illustrator action set"); //replace w your action details
var doc = app.activeDocument;
if (documents.length > 0){
// Create the illusrtratorSaveOptions object to set the AI options
var saveOpts = new EPSSaveOptions();
// Setting IllustratorSaveOptions properties.
saveOpts.embedLinkedFiles = embedImage = true;
saveOpts.embedAllFonts = embedFont = true;
saveOpts.includeDocumentThumbnails = true;
saveOpts.saveMultipleArtboards = false;
fullDocName = doc.fullName;
for (i=0; i<doc.layers.length; i++){
if (i-1<0) doc.layers[i].visible = true;
else {
doc.layers[i-1].visible = false;
doc.layers[i].visible = true;
}
if (doc.layers[i].locked == false) {
docName = doc.layers[i].name+".eps";
var saveName = new File ( "%1/%2 -- suffix.eps"); //replace " -- suffix" to whatever, keep .eps
doc.saveAs( saveName, saveOpts );
}
}
}
""";
var editedScript = strScript.replace("%1", psdpath).replace("%2", parentdirectory);
BridgeTalk.bringToFront("illustrator-25"); // switch view to illustrator to prevent crashing
var bt = new BridgeTalk;
//declare your illustrator version
bt.target = "illustrator-25";
bt.body = editedScript;
bt.send();

Photoshop Scripting JavaScript loop through layers problem

I have a script that does the following:
loops through layers,
saves each layer in a separate folder (name of folder same as layer name)
saved layer images have names "nameofthedocument, nameofthelayer.png"
Now I wanted to add text item on top of those layers while they are saving as separate pngs so that for gods sake you don't have to always look at the file name but instead there would be text in the PNG image rasterized and says "nameofthelayer" variable.
So for each layer of course different text should be inserted in the image.
i encountered weird problems once I tried to do that what seamigly looked easy.
HEre is the link with a video and an explanation of the code as well as what I did and why it messed up the script.
https://drive.google.com/drive/folders/1h2KAiEuruLY_PQ2JVhQAwINDYPvk9xHS?usp=sharing
Thank you folks, please help me out
Code, image and video explanation is all available in the link
CODE:
// NAME:
// SaveLayers
// DESCRIPTION:
// Saves each layer in the active document to a PNG or JPG file named after the layer.
// These files will be created in the current document folder.
// REQUIRES:
// Adobe Photoshop CS2 or higher
// VERSIONS:
// 27 March 2013 by Robin Parmar (robin#robinparmar.com)
// preferences stored in object
// auto-increment file names to prevent collisions
// properly handles layer groups
// header added
// code comments added
// main() now has error catcher
// counts number of layers
// many little code improvements
// 26 Sept 2012 by Johannes on stackexchange
// original version
// enable double-clicking from Finder/Explorer (CS2 and higher)
#target photoshop
app.bringToFront();
//alert(activeDocument.name);
function main() {
// two quick checks
if(!okDocument()) {
alert("Document must be saved and be a layered PSD.");
return;
}
var len = activeDocument.layers.length;
// user preferences
prefs = new Object();
prefs.fileType = "";
prefs.fileQuality = 0;
prefs.filePath = app.activeDocument.path;
prefs.count = 0;
saveLayers(activeDocument);
//toggleVisibility(activeDocument);
}
function saveLayers(ref) {
var len = ref.layers.length;
// rename layers top to bottom
for (var i = 0; i < len; i++) {
var layer = ref.layers[i];
if (layer.typename == 'LayerSet') {
// recurse if current layer is a group
saveLayers(layer);
} else {
// otherwise make sure the layer is visible and save it
layer.visible = true;
saveImage(layer.name);
layer.visible = false;
}
}
}
function getNameWithoutExtension(nameWithExt) {
var nameWithoutExtension = nameWithExt;
return nameWithoutExtension.split(".")[0];
}
function saveImage(layerName) {
var f = new Folder("D:/Process/0/"+layerName);
f.create();
//////////////// BROKEN PART I ADDED
#target photoshop
// Current layer name as text layer
var myDoc = app.activeDocument;
var myRulers = app.preferences.rulerUnits
app.preferences.rulerUnits = Units.PIXELS;
var OriginalLayerName = myDoc.activeLayer.name
var myLayerName = myDoc.activeLayer.name + "text";
var myLayerText = myDoc.artLayers.add()
myLayerText.kind = LayerKind.TEXT
var myText = myLayerText.textItem
myColor = new SolidColor
myColor.rgb.red = 255
myColor.rgb.green = 0
myColor.rgb.blue = 0
myLayerText.textItem.color = myColor
myText.position = [0,20] // Upper Left
myText.justification = Justification.LEFT
myText.size = 12
myText.contents = myLayerName
myLayerText.name = myLayerName // Or add a fixed string in quotes i.e. 'My Great Layer Name!'
app.preferences.rulerUnits = myRulers
//////////////////////////////END OF THE BROKN PART
//var handle = generateName(f.path + "/",layerName, ".png");
//alert(handle);
var handle = getUniqueName(prefs.filePath + "/"+ layerName +"/"+ getNameWithoutExtension(activeDocument.name) + ", " + layerName);
//alert(handle);
prefs.count++;
if(prefs.fileType=="PNG") {
SavePNG(handle);
} else {
SaveJPEG(handle);
}
}
function getUniqueName(fileroot) {
// form a full file name
// if the file name exists, a numeric suffix will be added to disambiguate
var filename = fileroot;
for (var i=1; i<100; i++) {
var handle = File(filename + "." + prefs.fileType);
if(handle.exists) {
filename = fileroot + "-" + padder(i, 3);
} else {
return handle;
}
}
}
function padder(input, padLength) {
// pad the input with zeroes up to indicated length
var result = (new Array(padLength + 1 - input.toString().length)).join('0') + input;
return result;
}
function SavePNG(saveFile) {
pngSaveOptions = new PNGSaveOptions();
activeDocument.saveAs(saveFile, pngSaveOptions, true, Extension.LOWERCASE);
}
function SaveJPEG(saveFile) {
pngSaveOptions = new PNGSaveOptions();
activeDocument.saveAs(saveFile, pngSaveOptions, true, Extension.LOWERCASE);
}
// file type
var saveOpt = [];
saveOpt[0] = "PNG";
saveOpt[1] = "PNG";
// png type
var pngtypeOpt = [1];
pngtypeOpt[0]=24;
pngtypeOpt[1]=24;
function okDocument() {
// check that we have a valid document
if (!documents.length) return false;
var thisDoc = app.activeDocument;
var fileExt = decodeURI(thisDoc.name).replace(/^.*\./,'');
return fileExt.toLowerCase() == 'psd'
}
function wrapper() {
function showError(err) {
alert(err + ': on line ' + err.line, 'Script Error', true);
}
try {
// suspend history for CS3 or higher
if (parseInt(version, 10) >= 10) {
activeDocument.suspendHistory('Save Layers', 'main()');
} else {
main();
}
} catch(e) {
// report errors unless the user cancelled
if (e.number != 8007) showError(e);
}
}
function generateName(filePath, layerName, ext) {
var generatedName = app.activeDocument.name;
var generatedName = generatedName.split(".")[0];
generatedName = generatedName + ", " + layerName;
return filePath + generatedName + ext;
}
wrapper();

Problem with counter in script Photoshop CS6 ver 13 64 bit

I have script that
PSD (activeDocument) in "3.Working folder saves jpg in draft folders in directory "../UserNameJobName/4.WIP/"
The problem is that everything works fine until I want to to create third draft folder (draft003). Then it saved again activeDocument in the same jpg file in draft002, instead of creating new folder draft003 and saving there respectivly. It seams that var draftCounter can't be higher than 2 value. I'm not sure where is a bug. What I know in photoshop CC it works without any problems.
[Link to folder structure zip]
https://www.dropbox.com/s/kbalzsubs2477jy/191130_WARGAMES_LUKKAR.zip?dl=0
Main file directory pic
Draft directory pic
code
#target photoshop;
var wipCounter = 1;
var fileNotFound = true;
main();
function main(){
//Get file information
var doc = app.activeDocument;
var docName = doc.name;
var docPath = doc.path;
//Get the percentage to scale by
var scaleValue = prompt("Enter the WIP JPEG scale percentage", "100");
//Figure out the location of the WIP folder
var savePath = docPath.toString();
savePath = savePath.slice(0,-10);
savePath = savePath + "/4.WIP/";
var currDoc = docName.toString();
currDoc = currDoc.slice(0,-4);
//global variables are defined here
//Look at the WIP folder and run a search for anything containing the word "draft"
//Define the location of the WIP folder
var inWIPFolder = new Folder(savePath);
//Look in each folder and create an array containing all of the information
var fileList = inWIPFolder.getFiles();
// Look at each array and sort the info out
for(var a=0; a<fileList.length; a++) {
//Exclude anything that is not a folder
if(fileList[a] instanceof Folder) {
//convert each foldername to string for editing
var fileName = fileList[a].toString();
var draftSearch = fileName.search("draft");
if(draftSearch > -1) {
var draftCounter = fileName.slice(draftSearch);
if(fileNotFound == true) {
searchDraftFolder(draftCounter, savePath, currDoc);
}
}
}
}
//Formatting the numbers
if(wipCounter < 10){
wipCounter = "00" + wipCounter.toString();
}else if(wipCounter >= 10 && wipCounter < 100) {
wipCounter = "0" + wipCounter.toString();
}
//Define the path of the draft folders
savePath = Folder(savePath +"/draft" + wipCounter);
//Check to see if the draft folders exists. If not, make one
if(!savePath.exists){
savePath.create();
}
//Define the WIP file name with the incremental counter
var wipFileName =savePath + "/" + currDoc + "_WIP" + wipCounter + ".jpg";
//Resize the file
doc.selection.selectAll();
var blankLayer = doc.artLayers.add();
blankLayer.name = "blankLayer";
doc.selection.copy(true);
doc.layers.getByName("blankLayer").remove();
//Make new doc to paste into
app.preferences.rulerUnits = Units.PIXELS;
//arguments are: Width, Height, resolution, filename, colourspce, documentfill
app.documents.add(UnitValue(doc.width, "PX"), UnitValue(doc.height, "PX"), doc.resolution, wipFileName, NewDocumentMode.RGB, DocumentFill.TRANSPARENT,1);
app.activeDocument.paste();
app.activeDocument.resizeImage(UnitValue(scaleValue, "PERCENT"), null, null, ResampleMethod.BICUBICSHARPER);
//Save a RGBJpeg
jpegFileSaver(app.activeDocument, new File(wipFileName), 10);
//Close the new document down
app.activeDocument.close(SaveOptions.DONOTSAVECHANGES);
//Deselect
doc.selection.deselect();
alert(currDoc + "WIP" + wipCounter + " saved.");
}
function searchDraftFolder(draftCounter, savePath, currDoc){
var fileSearch = -1;
//Define the location of each draft folder
var internalFolder = new Folder(savePath + "/" + draftCounter);
//Look in each folder and create an array containing all of the information
var internalFileList = internalFolder.getFiles();
// Look at each array and sort the info out
for(var a=0; a<internalFileList.length; a++) {
//Exclude anything that is not a file
if(internalFileList[a] instanceof File) {
// convert each filename to string for editing
var fileName = internalFileList[a].toString();
//Searching the current document name and replacing spaces with %20
var currDocStripped = currDoc.replace(/ /g, '%20');
//Checking files until a result greater than 0 appears
if(fileSearch === -1){
//search for the current file name
fileSearch = fileName.search(currDocStripped);
}
}
}
//if the filesearch does not return a result:
if(fileSearch === -1){
fileNotFound = true;
//if it does return a result:
} else {
//Slice the number off the draft folder
draftCounter = draftCounter.slice(-3);
//convert the string into an integer
draftCounter = parseInt(Number(draftCounter));
//increment the number up
wipCounter++;
//terminate the main loop
fileNotFound = false;
}
}
//A resuable JPEG save script
function jpegFileSaver(doc, saveFile, quality){
//define the save options
var saveOptions = new JPEGSaveOptions();
saveOptions.embedColorProfile = true;
saveOptions.formatOptions = FormatOptions.STANDARDBASELINE;
saveOptions.quality = quality;
//save the files
doc.saveAs(saveFile, saveOptions, true);
}
Thanks in advance.
Additional credits to code author http://jamesmcdonald3d.com/
The issue is with searchDraftFolder(). When it finds the already saved Great Map_wip in draft001, fileNotFound is set to false and your loop on line 39 terminates. That's why wipCounter is stuck on 2: it increments ones and that's it.
Here I rewrote this function a little bit, trying to make it simpler: all necessary loops are inside the function and I think it's easier to understand.
p.s. there was also an issue at least on CC: app.documents.add() was showing interface. That's because you were using a full path as a new document name and you can't use \-symbol in it, so Photoshop was suggesting a different name and showing it. I added a separate variable for document name without a path (line 49) to use in .add()
main();
function main()
{
//Get file information
var doc = app.activeDocument;
var docName = doc.name;
var docPath = doc.path;
var wipCounter;
//Get the percentage to scale by
var scaleValue = prompt("Enter the WIP JPEG scale percentage", "100");
//Figure out the location of the WIP folder
var savePath = docPath.toString();
savePath = savePath.slice(0, -10);
savePath = savePath + "/4.WIP/";
var currDoc = docName.toString();
currDoc = currDoc.slice(0, -4);
//global variables are defined here
//Look at the WIP folder and run a search for anything containing the word "draft"
//Define the location of the WIP folder
var inWIPFolder = new Folder(savePath);
// !! modifications
wipCounter = searchDraftFolder(inWIPFolder, currDoc)
//Formatting the numbers
if (wipCounter < 10)
{
wipCounter = "00" + wipCounter.toString();
}
else if (wipCounter >= 10 && wipCounter < 100)
{
wipCounter = "0" + wipCounter.toString();
}
//Define the path of the draft folders
savePath = Folder(savePath + "/draft" + wipCounter);
//Check to see if the draft folders exists. If not, make one
if (!savePath.exists)
{
savePath.create();
}
//Define the WIP file name with the incremental counter
var wipFileName = currDoc + "_WIP" + wipCounter + ".jpg";
var wipFilePath = savePath + "/" + wipFileName;
//Resize the file
doc.selection.selectAll();
var blankLayer = doc.artLayers.add();
blankLayer.name = "blankLayer";
doc.selection.copy(true);
doc.layers.getByName("blankLayer").remove();
//Make new doc to paste into
app.preferences.rulerUnits = Units.PIXELS;
//arguments are: Width, Height, resolution, filename, colourspce, documentfill
app.documents.add(UnitValue(doc.width, "PX"), UnitValue(doc.height, "PX"), doc.resolution, wipFileName, NewDocumentMode.RGB, DocumentFill.TRANSPARENT, 1);
app.activeDocument.paste();
app.activeDocument.resizeImage(UnitValue(scaleValue, "PERCENT"), null, null, ResampleMethod.BICUBICSHARPER);
//Save a RGBJpeg
jpegFileSaver(app.activeDocument, new File(wipFilePath), 10);
//Close the new document down
app.activeDocument.close(SaveOptions.DONOTSAVECHANGES);
//Deselect
doc.selection.deselect();
alert(currDoc + "_WIP" + wipCounter + " saved.");
}
// p is WIP path
// n is a name of the active doc without extension
function searchDraftFolder(p, n)
{
var fileList = p.getFiles(); // folders in wip folder
var counter = 1;
var drafts, fileName, i, k;
// for all the files found..
for (i = 0; i < fileList.length; i++)
{
//if a folder is found and its name has 'draft' in it
if (fileList[i] instanceof Folder && fileList[i].name.indexOf('draft') != -1)
{
//get files inside this draft folder
drafts = fileList[i].getFiles();
// for all files inside
for (k = 0; k < drafts.length; k++)
{
//'.name' gives us a URI-name, so replacing %20 with ' '. Probably should add more special symbols here if you use them
fileName = drafts[k].name.replace(/%20/g, ' ');
// if there's a file that starts with active doc name counter is incremented
if (fileName.indexOf(n) != -1)
{
counter++
}
}
}
}
return counter;
}
//A resuable JPEG save script
function jpegFileSaver(doc, saveFile, quality)
{
//define the save options
var saveOptions = new JPEGSaveOptions();
saveOptions.embedColorProfile = true;
saveOptions.formatOptions = FormatOptions.STANDARDBASELINE;
saveOptions.quality = quality;
//save the files
doc.saveAs(saveFile, saveOptions, true);
}

Importing images with only specific file extension into Photoshop

I am new to JavaScripting (have learned allot from this site!). I have existing code (from someone else) that successfully brings in all images into photoshop from a user selected folder. I would like to modify the code to only bring in specific file extensions (Jpg, png, tiff...etc). I found a great example of code from this site below of what I would like to do.
var distilledFileList = [];
for (var i = 0; i < fileList.length; i++){
if (/\.(?:jpe?g|png|gif|psd)$/i.test(fileList[i].name)){
distilledFileList.push(fileList[i]);
}
}
Original code found here
I have not figured out how to implement a version of this successfully into what I already have. Here is the main section of my code I believe where the modification needs to be added.
#target photoshop
app.bringToFront();
// Dialog for user to choose folder of documents to process
var inputFolderArray = [];
do {
var inputFolder = Folder.selectDialog("Select a folder of documents to process");
if(inputFolder != null) {
inputFolderArray.push(inputFolder);
}
}
while(inputFolder != null
|| inputFolder != undefined)
// Pulls images from inputFolder
for (var j = 0; j < inputFolderArray.length; j++) {
var filesList = inputFolderArray[j].getFiles();
var outputDirectory = inputFolderArray[j] + '/';
}
function PSDCreate(frameArrays, outputDirectory) {
directory = outputDirectory + '/';
//var outputLocation = inputFolder + "/" + directory;
var outputFileName = '';
if (frameArrays != null) {
// Get all the files in the folder
var fileList = frameArrays;
var k = 0;
for (var i = 0; i < fileList.length; i++) {
if (fileList[i] instanceof File && fileList[i].hidden == false) {
var fileName = fileList[i].name;
var docRef = open(fileList[i]);
if(k == 0) {
k++;
outputFileName = RemoveExtension(docRef.name);
app.displayDialogs = DialogModes.NO;
}
}
}
// Execute changes to images in photoshop here..
Does someone know how to implement a version of the example code to what I already have by chance? Any help is greatly appreciated!
If I understand correctly, you want user to select several folders and than process files of all these folders. First of all, here
// Pulls images from inputFolder
for (var j = 0; j < inputFolderArray.length; j++) {
var filesList = inputFolderArray[j].getFiles();
var outputDirectory = inputFolderArray[j] + '/';
}
filesList will be overwritten with every new folder, you'll get a list of files from the last folder selected only. I'd change this to
// Pulls images from inputFolder
var files = []
for (var j = 0; j < inputFolderArray.length; j++)
{
var filesList = inputFolderArray[j].getFiles();
for (var i = 0; i < filesList.length; i++)
{
if (/\.(?:jpe?g|png|gif|psd)$/i.test(filesList[i].name)) files.push(filesList[i]); //get needed files from folders
}
}
alert(files); // < array of files
if you only need to open these files, you can replace files.push(filesList[i]); with app.open(fileList[i]);

Dynamically generated javascript img tag firefox issue

I'm having trouble with a screen containing dynamically generated images, when viewed in Chrome it functions as expected, images get generated no problem. However in Firefox none of the images end up being generated and the user is shown a set of image not loaded boxes.
function popupPermanentOverlay_Walking(locationName) {
var title = "Walking to "+locationName;
var content = "Content_Text<div class='walkimg-container'><img class='walkimg' src='images/anim/walkimg.gif'/>";
for(var i = 0; i<50; i++)
{
var filename = "";
var type=random(0,5);
if (type==0)
filename = "tree";
else if (type==1)
filename = "tree";
else if (type==2)
filename = "shrub";
else if (type==3)
filename = "shrub";
else if (type==4)
filename = "shrub";
else if (type==5)
filename = "baretree";
if (filename == "tree")
filename+=random(1,6);
else if (filename == "shrub")
filename+=random(1,3);
else if (filename == "baretree")
filename+=random(1,7);
var y = random(-60, 60);
content+="<img class='walking-prop' src='images/anim/props/"+filename+".gif' style='bottom:"+(y-7)+"px; left:"+random(-50,720)+"px;z-index:"+(15000-y)+";' />";
}
for(var i = 0; i<100; i++)
{
var filename = "grass";
if (random(1,2)==1)
filename+=random(1,6);
else
filename+=random(3,6);
var y = random(-100, 100);
content+="<img class='walking-prop' src='images/anim/props/"+filename+".gif' style='bottom:"+(y)+"px; left:"+random(-180,720)+"px;z-index:"+(10000-y)+";' />";
}
content+="</div>";
popupPermanentOverlay(title, content, "walking-popup");
$(".walkimg").animate({left: "+=600px"}, 20000, "linear");
}
I know Firefox sometimes has an issue of loading the page before images are ready, but I have tried adding a check to ensure it has loaded to no effect.
Ideally I would like to avoid preloading the images which I know is a potential fix for this.

Categories

Resources