Importing images with only specific file extension into Photoshop - javascript

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]);

Related

JavaScript upload more files one by one

I have wrote this javascript code to upload files. The problem is it uploads all the files at the same time. I want to upload them one by one. I have been trying to do it for three hours.
$(document).ready(function() {
$(':file').change(function() {
$("#modsform").hide();
for (var i = 0; i < this.files.length; i++) {
var file = this.files[i];
showFile(file, i);
}
for (var i = 0; i < this.files.length; i++) {
var file = this.files[i];
sendFile(file, i);
}
});
});
full code:
http://jsfiddle.net/yhq83r6o/3/

Illustrator edit link filepath via 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.

Illustrator Script: Export Single Layer to SVG

I have been trying to get a script going that is able to export a specific illustrator file to a SVG format. I have been referencing this Adobe forum post about a method of doing this and implemented it somewhat succesfully, see below:
var singleLayer,
doc,
path = 'C:/Users/lukeb/Desktop/New folder',
type = ExportType.SVG,
options = new ExportOptionsSVG(),
layerAmount;
doc = this.myApp;
singleLayer = this.myApp.layers["buttons"];
options.embedRasterImages = false;
options.cssProperties = SVGCSSPropertyLocation.PRESENTATIONATTRIBUTES;
options.fontSubsetting = SVGFontSubsetting.None;
options.documentEncoding = SVGDocumentEncoding.UTF8;
options.coordinatePrecision = 4;
layerAmount = doc.layers.length;
hideAllLayers();
for (var i = layerAmount - 1, k = 0; i >= 0; i--, k++) {
if (this.myApp.layers[i] === singleLayer) {
var file;
singleLayer.visible = true;
file = new File(path + "/" + singleLayer);
this.myApp.exportFile(file, type, options);
singleLayer.visible = false;
}
}
showAllLayers();
function hideAllLayers() {
for(var i = 0; i < layerAmount; i++) {
doc.layers[i].visible = false;
}
}
function showAllLayers() {
for(var i = 0; i < layerAmount; i++) {
doc.layers[i].visible = true;
}
}
This code runs perfectly, to an extent. It singles out the layer in my layer library and turns all of them off except that one. But for some reason it does not export just that one layer as an SVG, it exports a whole lot, if not all of them. Is there something missing with this? There isnt a lot of documentation around all of this so wasnt too sure of a fool proof solution to just get a single layer.

Change selected files in input element with JQuery

I need to change selected files in input:file element with Jquery. Firstly, user select files. There is a file size control in input:file change event. So, if control return false selected file should be removed in file_list. I searched this and try something for 3 - 4 hours. But not achieved still. I hope someone can help me.
Here is my function.
function handleFiles2() {
var names = [];
var newList = [];
var text = '';
var x = 0;
var fsize = 0;
var files = $(".fileUpBasvuru").get(0).files;
for (var i = 0; i < files.length; ++i) {
fsize = parseInt(files[i].size);
if (fsize > 102400) {
newList.push(files.item(i));
names.push(files[i].name);
}
}
$(".fileUpBasvuru").get(0).files = newList;
$(".file_list").html(text);
};

Photoshop Scripting: How to make page numbers

Hello I was wondering if anyone can help me write a Photoshop script that will display a number and save the document incrementally?
I got to here so far:
if(app.documents.length != 0){
var doc = app.activeDocument;
for(i = 0; i < doc.artLayers.length; ++i){
var layer = doc.artLayers[i];
if(layer.kind == LayerKind.TEXT){
layer.textItem.contents = 1;
layer.textItem.size = 20;
}
}
}
But I'm having trouble writing the content with increments. I want it so that the page number on my document increases by 1.
It isn't entirely clear what you are after. This will increment the number shown, but every text layer it encounters will get numbered.
if(app.documents.length != 0){
var doc = app.activeDocument;
var j = 1;
for(i = 0; i < doc.artLayers.length; ++i){
var layer = doc.artLayers[i];
if(layer.kind == LayerKind.TEXT){
layer.textItem.contents = j;
layer.textItem.size = 20;
j++;
}
}
}

Categories

Resources