I've created to a simple illustrator script to loop through the artboards and export each as a PNG back into the folder that the original illustrator file is in. At least I thought I had. I don't need to do anything complicated with layers or different formats this is just a speed up production sort of a thing. I'm a bit rusty on .jsx and appreciate there are similar solutions out there, but I can't get this to run. It seems to fail on the doc.ExportFile line but I really can't see what I'm doing wrong. I'd appreciate anyone taking a look:
var doc = activeDocument;;//Gets the active document
var numArtboards = doc.artboards.length;//returns the number of artboards in the document
var basePath = new File($.fileName).parent.fsName;
$.writeln(doc)
var options;
options = new ExportOptionsPNG24();
options.artBoardClipping = true;
options.matte = false;
options.horizontalScale = 100;
options.verticalScale = 100;
options.transparency = true;
for (var i = 0; i < numArtboards; i++ ) {
doc.artboards.setActiveArtboardIndex( i );
var artboardName = doc.artboards[i].name;
var destFile = new File('/' + artboardName + ".png");
doc.exportFile(destFile, ExportFormat.PNG24 , options);
}
The main problem seemed to be that you hve to have a destination path with the file name. This now seems to work: (You may need to altter the fileNamr generation as code just gets the first nune letters of a filename)
var doc = app.activeDocument;;//Gets the active document
var fleName = doc.name.slice(0, 9)//Get the file code number not the full name;
var numArtboards = doc.artboards.length;//returns the number of artboards in the document
var filePath = (app.activeDocument.fullName.parent.fsName).toString().replace(/\\/g, '/');
$.writeln("fleName= ",fleName)
$.writeln("numArtboards= ",numArtboards)
$.writeln("filePath= ",filePath);
var options = new ExportOptionsPNG24();
for (var i = 0; i < numArtboards; i++ ) {
doc.artboards.setActiveArtboardIndex( i );
options.artBoardClipping = true;
options.matte = false;
options.horizontalScale = 100;
options.verticalScale = 100;
options.transparency = true;
var artboardName = doc.artboards[i].name;
$.writeln("artboardName= ", artboardName);
var destFile = new File(filePath + "/" + fleName + " " + artboardName + ".png");
$.writeln("destFile= ",destFile);
doc.exportFile(destFile,ExportType.PNG24,options);
}
Related
i have a really annoyong problem.
var Scriptfile = new File($.fileName);
var basePath = Scriptfile.path;
var topFolder = new Folder(basePath+"/actions");
var fileandfolderAr = scanSubFolders(topFolder,/\.(atn)$/i);
var fileList = fileandfolderAr[0];
for (var a = 0 ;a < fileList.length; a++) {
var atnFile = new File(fileList[a]);
alert(atnFile.name);
var rex = new RegExp (decodeURI(atnFile.name.replace(/\.[^\.]+$/, '')), "g");
if (!atnFile.exists) {
alert("Your ActionSet does not exist!\nPlease contact your administrator.");
return false;
}
var actionList = getActionSets();
//if ActionSet Exists remove it.
var flag = 0;
for (var d in actionList) {
if (decodeURI(actionList[d]).match(rex)) {
flag = 1;
continue;
}
}
if (!atnFile.exists) {
alert("File does not exist");
return false;
}
if (flag == 0) {
app.load(atnFile);
}
}
This piece of code is working very well if the atn file isn't placed in a folder or subfolder which contains a white space in it's name.
If i have a folder name like "photoshop script" it won't load my atn file.
Any ideas?
Thank you a lot!
It seems that nobody knows how to solve this, you big programmers. I found the solution. All i have to do is to decode the path to the file. I just replaced the var atnFile = new File(fileList[a]); with var atnFile= new File(decodeURI(fileList[a])); . I hope this will help someone sometime.
I (with help) created a script that creates folders, copies a file 15 times, renames the file, and puts the new renamed files into the folders it created.
I am trying to edit the script so it uses .setValue to edit the new file it has copied, setting the "I9" cell of the new copied files to:
.setValue('=IMPORTRANGE("ID", "Question Details!C' + j + 3 + ':AX' + j + 3 + ')');
I don't know how to edit the newly created spreadsheets as its looping through and creating them. I'm not sure how to edit a sheet that is an "object" in the script. When I would run the script, it would say it couldn't get copySheet.getRange(1,9,1,1); of an object.
Now, I was trying to use "J" from the for loop in the new formula added to this cell so I can get it to increase dynamically according to the value of "J" and I can't get it to work. (This for loop is used to increase the number in the name of the sheet already) I'm sure that my syntax is way off. But, forgive me. I am still learning and really enjoy learning from the help on SO.
I also wondered if it made more sense to set it to loop through the these new folders/files afterwards and edit the "I9" cell in each? Not sure...
SCRIPT BELOW
The code that I tried to add in script is notated at the bottom of the script. I'm sure it's way off base, but I'm trying. Any help you guys could give me would be much appreciated!
Thanks!
Brandon
var folderIds = [];
function onOpen(e) {
SpreadsheetApp.getUi()
.createMenu('Data System Tool')
.addItem('Create Data System Folders', 'copyAndRenameTemplate')
.addToUi();
}
function copyAndRenameTemplate() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var theSheet = ss.getSheetByName('Sheet1');
var rangeOfFileNames = ss.getRange("B4:B");
var twoD_Array = rangeOfFileNames.getValues();
var arrayOfFileNames = twoD_Array.join().split(",");
var folderType = theSheet.getRange(2,1);
var cell = folderType.getValue();
Logger.log(folderType);
Logger.log(cell);
// throw new Error('Script Halted! Check out the logs!!');
var fldrNamesRng = theSheet.getRange(4,1,theSheet.getLastRow()-3,1);
Logger.log('fldrNamesRng: ' + fldrNamesRng);
var folderNames = fldrNamesRng.getValues();
Logger.log('folderNames: ' + folderNames);
var oneD_FolderNames = folderNames.join().split(",");
Logger.log('oneD_FolderNames: ' + oneD_FolderNames);
makeTheFolders(oneD_FolderNames);
putFilesIntoFolders(oneD_FolderNames);
};
function makeTheFolders(theFolderNames,cell) {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var theSheet = ss.getSheetByName('Sheet1');
var folderType = theSheet.getRange(2,1);
var cell = folderType.getValue();
var i=0,
folderObj;
for (i=0;i<theFolderNames.length;i+=1) {
folderObj = DriveApp.createFolder(theFolderNames[i] + " " + cell);
folderIds.push(folderObj.getId())
};
};
function putFilesIntoFolders(arrayOfFolderNames,theFolderNames,cell) {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var theSheet = ss.getSheetByName('Sheet1');
var folderType = theSheet.getRange(2,1);
var cell = folderType.getValue();
var file = DriveApp.getFileById("File to Copy");
var dest_folder = "";
var baseFileName = "",
newfile,
newFileName = "",
i=0,
j=0;
for (i=0;i<arrayOfFolderNames.length;i+=1) {
var source_folder = DriveApp.getFolderById("Folder that has File to be Copied");
dest_folder = DriveApp.getFolderById(folderIds[i]);
Logger.log('dest_folder' + dest_folder);
baseFileName = arrayOfFolderNames[i];
for (j=1; j<16; j+=1) {
var newFileName = baseFileName + " " + cell + " " + j.toString();
var fileCopy = file.makeCopy();
/* Code I tried */
// var copyID = fileCopy.getId();
// var copySs = DriveApp.getFileById(copyID);
// var copySheet = copySs.getSheets()[0];
// var copyCell = copySheet.getRange(1,9,1,1);
// copyCell.setValue('=IMPORTRANGE("ID", "Question Details!C' + j + 3 + ':AX' + j + 3 + ')');
var namedFileCopy = fileCopy.setName("_" + newFileName);
if (j<10) {
dest_folder.addFile(namedFileCopy);
source_folder.removeFile(fileCopy);
} else {
var namedFileCopy = fileCopy.setName(newFileName);
dest_folder.addFile(namedFileCopy);
source_folder.removeFile(fileCopy);
};
};
};
};
You've got the right idea, you just need to make sure you open the new (copied) spreadsheet as a Spreadsheet object so that you can use Spreadsheet methods on it.
Instead of:
var copySs = DriveApp.getFileById(copyID);
Use:
var copySs = SpreadsheetApp.openById(copyID);
By doing so, copySs will be a variable that represents a Spreadsheet object, and the other lines you already wrote will actually make sense!
var copySheet = copySs.getSheets()[0];
var copyCell = copySheet.getRange(1,9,1,1);
copyCell.setValue('=IMPORTRANGE("ID", "Question Details!C' + j + 3 + ':AX' + j + 3 + ')');
I'm hacking together a little Dropbox image slideshow. I use the Dropbox Public folder to share the index.html file which looks in the 'img' folder for a bunch of images to create slides.
I do this with the following, it's hacky but works
var findFiles = function(slideLimit){
var limit = slideLimit;
var img = [];
for(var i = 1; i < limit; i++){
var src = "<li class='slide slide-"+i+"'><img src='img/"+i+".png' onerror='imgError(this);''></li>"
$('.frame ul').append(src);
}
}
That works great, but I'd like to provide a solution that doesn't rely on the user having to use .png.
I was hoping omitting the extension would work on Dropbox but turns out no:
var src = "<li class='slide slide-"+i+"'><img src='img/"+i+"' onerror='imgError(this);''></li>"
I've been racking my brains, ideally I'd like
if( mimeType = png)
i + '.png'
else if (mimeType = gif)
i + '.gif'
etc
Bit stuck for solutions. Anyone got any good ideas? Might require me taking different a different direction...
Best way, make the users tell you the extension
var findFiles = function(slideLimit, ext){
var limit = slideLimit,
img = [],
lis = [];
ext = ext || "png";
for (var i = 1; i < limit; i++) {
lis.push("<li class='slide slide-"+i+"'><img src='img/"+i+"."+ext+"' onerror='imgError(this);''></li>");
}
$('.frame ul').append(lis.join(""));
}
Ping the server for the file, downside it takes time to keep hitting the server to see if the file it there
var findFiles = function(slideLimit){
var limit = slideLimit,
img = [],
lis = [],
extList = ["png","gif"];
function testExt () {
var ext = extList.shift();
if (ext) {
var img = new Image();
img.onload = function () {
load(ext);
};
img.onerror = testExt;
img.src="img/1." + ext;
}
}
function load (ext){
for (var i = 1; i < limit; i++) {
lis.push("<li class='slide slide-"+i+"'><img src='img/"+i+"."+ext+"' onerror='imgError(this);''></li>");
}
$('.frame ul').append(lis.join(""));
}
testExt();
}
[note both code snipplets are untested, wrote them here in the editor]
I'm having trouble writing a js script in indesign cs6 to export my formatted images. the code below (found on this website and slightly modified) only opens the document.
ideally the script would loop through all of the formatted/cropped images in my document and export them into a new folder on the desktop, but with the original file names.
any help would be much appreciated:
test();
function test(){
var myDoc = app.open('/Users/StudioA/Desktop/file.indd');
var myGroups = myDoc.groups;
//for each group...
for (var i = 0;i < myGroups.length; i++){
// for each rectangle in the group...
for(var r = 0; r< myGroups[i].rectangles.length; r++){
var myRect = myGroups[i].rectangles[r];
app.jpegExportPreferences.exportResolution = 300;
app.jpegExportPreferences.jpegQuality = JPEGOptionsQuality.MAXIMUM;
//give it a unique name
var myFile = new File('/Users/StudioA/Desktop/Export/' + myRect.name + '.jpg');
myRect.exportFile(ExportFormat.JPG, myFile);
}
}
}
The file name isn't located on the rectangle but on the link related to the placed graphic.
This should do what you want given an open document:
test();
function test() {
var myDoc = app.activeDocument, apis = myDoc.allPageItems, rect, fileName;
while ( rect = apis.pop() )
{
if ( !(rect instanceof Rectangle) || !rect.graphics[0].isValid ){ continue; }
fileName = File ( rect.graphics[0].itemLink.filePath ).name;
fileName = fileName.replace( /\.[a-z]{2,4}$/i, '.jpg' );
app.jpegExportPreferences.exportResolution = 300;
app.jpegExportPreferences.jpegQuality = JPEGOptionsQuality.MAXIMUM;
//give it a unique name
var myFile = new File (Folder.desktop+"/"+ fileName);
rect.exportFile(ExportFormat.JPG, myFile);
}
}
Just adding my verbose version of this, which works from the current selection in InDesign and provides console feedback. It renames the images with the prefix "crop_" and saves them to ~/temp
exportSelectedImages();
function exportSelectedImages() {
// configure export settings
app.jpegExportPreferences.exportResolution = 72;
app.jpegExportPreferences.jpegQuality = JPEGOptionsQuality.HIGH;
// collect selected objects
var selected = app.activeDocument.selection;
$.writeln("Got " + selected.length + " selected objects...");
// process selected objects
for (var i = 0; i < selected.length; i++) {
var cursor = selected[i];
var img = cursor.images;
$.writeln("Processing #" + (i+1) + "/" + selected.length);
$.writeln("\t Type: " + cursor.constructor.name);
// verify if object contains an image or not
if (cursor.images.length > 0) {
var img = cursor.images[0];
$.writeln("\t Contains image of type " + img.imageTypeName);
var imageFileName = cursor.images[0].itemLink.name;
$.writeln("\t File Name: " + imageFileName);
} else {
$.writeln("\t Not an image");
}
// save the object to a jpeg in path specified below
var myFile = new File('~/temp/' + "crop_" + imageFileName + '.jpg');
cursor.exportFile(ExportFormat.JPG, myFile);
}
$.writeln("Done.");
}
I have a folder with a lot of subfolders, each with a bunch of TIFs and PSD files inside. Some of these have transparency in them while some don't. These files vary massively in size.
I need all the files to be turned into JPGs, or if they contain transparency, PNGs. I require the files to be 200kb or less and don't really mind how large they are as long as they aren't scaled up.
Someone on a forum (who I'm insanely thankful for) wrote a fair bit of code for it, which my friend modified to suit exactly what I was asking and we're nearly there now.
It worked fine, the only problem being that a lot of images came out 1x1 pixel and a solid block of colour.
We've found this was consistently happening with the same images for some reason, but couldn't work out what exactly it was in these images.
Now Mr forum blokey ( http://www.photoshopgurus.com/forum/members/paul-mr.html ) modified the script and it now seems to work fine with PSDs.
It's working with TIFs with transparency but some of the TIFs with 100% opacity it just won't work on. I can't find much that's consistent with these files other than the colour blue, though this just could be a massive coincidence and probably is (there's a lot of blue in the images I've been dealing with).
Below is a link to the thread in which the code was first written. Paul MR seems to think the colorsampler bit is a little suspect so perhaps that's what's causing the problems (blueness?).
http://www.photoshopgurus.com/forum/photoshop-actions-automation/34745-batching-tiffs-jpg-png-w-automatic-resize-based-filesize.html
I wish I could do a little more to try and work this out myself but I've barely a speck of understanding on this stuff, I just know when there's a situation where a bit of scripting could help out.
Below is the script as it currently stands:
#target PhotoshopString.prototype.endsWith = function(str) {
return (this.match(str + "$") == str)
} String.prototype.startsWith = function(str) {
return this.indexOf(str) == 0;
};
var desiredFileSize = 200000;
app.bringToFront();
app.displayDialogs = DialogModes.NO;
main();
//app.displayDialogs = DialogModes.YES;
function main() {
var topLevelFolder = Folder.selectDialog("Please select top level folder.");
if (topLevelFolder == null)return;
var FileList = [];
getFileList(topLevelFolder);
var startRulerUnits = app.preferences.rulerUnits;
app.preferences.rulerUnits = Units.PIXELS;
for (var f in FileList) {
app.open(FileList[f]);
activeDocument.changeMode(ChangeMode.RGB);
try {
activeDocument.mergeVisibleLayers();
} catch(e) {} var Name = decodeURI(app.activeDocument.name).replace(/.[^.] + $ /, '');
if (hasTransparency(FileList[f])) {
var saveFile = File(FileList[f].path + "/" + Name + ".png");
SavePNG(saveFile);
app.activeDocument.close(SaveOptions.DONOTSAVECHANGES);
} else {
var saveFile = File(FileList[f].path + "/" + Name + ".jpg");
SaveForWeb(saveFile, 80);
app.activeDocument.close(SaveOptions.DONOTSAVECHANGES);
} app.preferences.rulerUnits = startRulerUnits;
} function getFileList(folder) {
var fileList = folder.getFiles();
for (var i = 0; i < fileList.length; i++) {
var file = fileList[i];
if (file instanceof Folder) {
getFileList(file);
} else {
if ((file.name.endsWith("tiff") || file.name.endsWith("tif") || file.name.endsWith("psd")) && ! file.name.startsWith("._"))FileList.push(file);
}
}
} alert(FileList.length + " files have been modified.");
} function hasTransparency(file) {
if (file.name.endsWith("tiff") || file.name.endsWith("tif")) {
var sample = app.activeDocument.colorSamplers.add([new UnitValue(1.5, 'px'), new UnitValue(1.5, 'px')]);
try {
sample.color.rgb.hexValue;
sample.remove();
return false;
} catch(e) {
sample.remove();
return true;
}
} var doc = activeDocument;
if (doc.activeLayer.isBackgroundLayer)return false;
var desc = new ActionDescriptor();
var ref = new ActionReference();
ref.putProperty(charIDToTypeID("Chnl"), charIDToTypeID("fsel"));
desc.putReference(charIDToTypeID("null"), ref);
var ref1 = new ActionReference();
ref1.putEnumerated(charIDToTypeID("Chnl"), charIDToTypeID("Chnl"), charIDToTypeID("Trsp"));
desc.putReference(charIDToTypeID("T "), ref1);
executeAction(charIDToTypeID("setd"), desc, DialogModes.NO);
var w = doc.width.as('px');
var h = doc.height.as('px');
var transChannel = doc.channels.add();
doc.selection.store(transChannel);
if (transChannel.histogram[255] != (h * w)) {
transChannel.remove();
return true;
} else {
transChannel.remove();
return false;
}
};
function SavePNG(saveFile) {
pngSaveOptions = new PNGSaveOptions();
activeDocument.saveAs(saveFile, pngSaveOptions, true, Extension.LOWERCASE);
var actualFilesize = saveFile.length;
var ratio = desiredFileSize / actualFilesize;
if (ratio < 1) {
var imageScale = Math.sqrt(ratio);
activeDocument.resizeImage(activeDocument.width * imageScale, activeDocument.height * imageScale, activeDocument.resolution, ResampleMethod.BICUBICSMOOTHER);
activeDocument.saveAs(saveFile, pngSaveOptions, true, Extension.LOWERCASE);
}
}
function SaveForWeb(saveFile, jpegQuality) {
var sfwOptions = new ExportOptionsSaveForWeb();
sfwOptions.format = SaveDocumentType.JPEG;
sfwOptions.includeProfile = false;
sfwOptions.interlaced = 0;
sfwOptions.optimized = true;
sfwOptions.quality = jpegQuality;
activeDocument.exportDocument(saveFile, ExportType.SAVEFORWEB, sfwOptions);
var actualFilesize = saveFile.length;
var ratio = desiredFileSize / actualFilesize;
if (ratio < 1) {
var imageScale = Math.sqrt(ratio);
activeDocument.resizeImage(activeDocument.width * imageScale, activeDocument.height * imageScale, activeDocument.resolution, ResampleMethod.BICUBICSMOOTHER);
activeDocument.exportDocument(saveFile, ExportType.SAVEFORWEB, sfwOptions);
}
}