Photoshop/Javascript - EPS to Tiff file conversion and removing duplicates - javascript

Hey all so I have this script that converts EPS files to Tiffs in Photoshop.
At present it allows you to pick a folder of files to be converted and creates a new folder in that for the Tiff files. I had tried creating the Tiffs in the same folder without creating an extra folder but this seemed to mess with the original EPS file. The conversion was happening fine but it was taking the data out of the EPS and saving it like a blank file. Since I put the new converted Tiff files in a folder it is creating a copy of the original EPS in there too which I don't need.
Basically I need to convert all the EPS files in a folder to Tiffs but do not want to mess with the original EPS and do not want an additional copies of the file.
The script I have at present is as follows:
#include "~/AppData/Local/wbmUtils/lib/underscore.js";
//-------------- declare measurement in pixels and declare vars for HxW --------------\\
app.preferences.rulerUnits = Units.PIXELS;
var height =0;
var width = 0;
//-------------- select input and output folders --------------\\
alert("Choose a folder of EPS's");
var inPath = Folder.selectDialog();
var outPath = inPath+'/Tiffs';
$.writeln(inPath);
$.writeln(outPath);
//-------------- get full image list from input folder --------------\\
var inputs = getImageList (inPath);
function getImageList (dirPath)
{
var contents = dirPath.getFiles();
var imageList=[];
_.each(contents, function(item)
{
imageList.push(item.toString());
})
return imageList;
}
//-------------- create new folder for files --------------\\
$.writeln(inputs);
var imageFolderName = outPath;
var imageFolder = Folder(imageFolderName);
if(!imageFolder.exists) imageFolder.create();
_.each(inputs, function(input)
{
$.writeln("height: " + height + " width: " + width);
var imgWithExt = _.last(input.split('/'))
doPreviews(input, imageFolderName +'/' + imgWithExt);
var of = new File(input);
of.copy (imageFolderName +'/' + imgWithExt.split('.')[0] + '.eps');
})
//-------------- main conversion function --------------\\
function doPreviews(input, output)
{
var idOpn = charIDToTypeID("Opn ");
var desc4 = new ActionDescriptor();
var idnull = charIDToTypeID("null");
desc4.putPath(idnull, new File(input));
var idAs = charIDToTypeID("As ");
var desc5 = new ActionDescriptor();
var idRslt = charIDToTypeID("Rslt");
var idRsl = charIDToTypeID("#Rsl");
desc5.putUnitDouble(idRslt, idRsl, 300.000000);
var idAntA = charIDToTypeID("AntA");
desc5.putBoolean(idAntA, true);
var idEPSG = charIDToTypeID("EPSG");
desc4.putObject(idAs, idEPSG, desc5);
executeAction(idOpn, desc4, DialogModes.NO);
var idMk = charIDToTypeID("Mk ");
var desc7 = new ActionDescriptor();
var idnull = charIDToTypeID("null");
var ref1 = new ActionReference();
var idDcmn = charIDToTypeID("Dcmn");
ref1.putClass(idDcmn);
desc7.putReference(idnull, ref1);
var idUsng = charIDToTypeID("Usng");
var ref2 = new ActionReference();
var idHstS = charIDToTypeID("HstS");
var idCrnH = charIDToTypeID("CrnH");
ref2.putProperty(idHstS, idCrnH);
desc7.putReference(idUsng, ref2);
executeAction(idMk, desc7, DialogModes.NO);
height = app.activeDocument.height;
width = app.activeDocument.width;
if (height > width)
{
$.writeln("IS HIGHER THAN WIDE");
var idImgS = charIDToTypeID("ImgS");
var desc8 = new ActionDescriptor();
var idHght = charIDToTypeID("Hght");
var idPxl = charIDToTypeID("#Pxl");
desc8.putUnitDouble(idHght, idPxl, 6500.000000);
var idscaleStyles = stringIDToTypeID("scaleStyles");
desc8.putBoolean(idscaleStyles, true);
var idCnsP = charIDToTypeID("CnsP");
desc8.putBoolean(idCnsP, true);
var idIntr = charIDToTypeID("Intr");
var idIntp = charIDToTypeID("Intp");
var idautomaticInterpolation = stringIDToTypeID("automaticInterpolation");
desc8.putEnumerated(idIntr, idIntp, idautomaticInterpolation);
executeAction(idImgS, desc8, DialogModes.NO);
} else {
$.writeln("IS WIDER THAN HIGH");
var idImgS = charIDToTypeID("ImgS");
var desc32 = new ActionDescriptor();
var idWdth = charIDToTypeID("Wdth");
var idPxl = charIDToTypeID("#Pxl");
desc32.putUnitDouble(idWdth, idPxl, 6500.000000);
var idscaleStyles = stringIDToTypeID("scaleStyles");
desc32.putBoolean(idscaleStyles, true);
var idCnsP = charIDToTypeID("CnsP");
desc32.putBoolean(idCnsP, true);
var idIntr = charIDToTypeID("Intr");
var idIntp = charIDToTypeID("Intp");
var idautomaticInterpolation = stringIDToTypeID("automaticInterpolation");
desc32.putEnumerated(idIntr, idIntp, idautomaticInterpolation);
executeAction(idImgS, desc32, DialogModes.NO);
}
var idMk = charIDToTypeID("Mk ");
var desc20 = new ActionDescriptor();
var idnull = charIDToTypeID("null");
var ref4 = new ActionReference();
var idDcmn = charIDToTypeID("Dcmn");
ref4.putClass(idDcmn);
desc20.putReference(idnull, ref4);
var idUsng = charIDToTypeID("Usng");
var ref5 = new ActionReference();
var idHstS = charIDToTypeID("HstS");
var idCrnH = charIDToTypeID("CrnH");
ref5.putProperty(idHstS, idCrnH);
desc20.putReference(idUsng, ref5);
executeAction(idMk, desc20, DialogModes.NO);
var idCls = charIDToType("Cls ");
executeAction(idCls, desc20, DialogModes.NO);
//-------------- tiff options --------------\\
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;
app.activeDocument.saveAs(File(output.split('.')[0]+'.tiff'), tiffSaveOptions, true);
app.activeDocument.close(SaveOptions.DONOTSAVECHANGES);
app.activeDocument.close(SaveOptions.DONOTSAVECHANGES);
app.activeDocument.close(SaveOptions.DONOTSAVECHANGES);
}
//-------------- success message --------------\\
alert("ALL DONE!")

I would be inclined to do this with ImageMagick which is installed on most Linux distros and is available for OSX and Windows.
So, at the command-line in your Terminal:
mkdir TIFFs # Make the output directory called "TIFFs"
mogrify -format tif -path TIFFs *.eps # Convert all EPS to TIFFs/*.tif

Related

Photoshop script select all layers with same name as current layer

I need a photoshop script that selects all layers with the same name as the currently selected layer. The following code does the job:
if (app.documents.length > 0) {
activeDocument.suspendHistory('stuff', 'main()');
function main(){
if(!documents.length) return;
var myDoc = app.activeDocument;
var theName = myDoc.activeLayer.name;
var theResults = new Array;
selectAllLayers();
var selectedLayers = getSelectedLayersIdx();
for(var a = 0; a < selectedLayers.length; a++){
var thisName = layerName(Number(selectedLayers[a]));
if (thisName == theName) {
theResults.push(Number(selectedLayers[a]))
};
};
selectLayerByIndex(theResults[0], false);
for (var m = 1; m < theResults.length; m++) {
selectLayerByIndex(theResults[m], true);
};
}
};
function getSelectedLayersIdx(){
var selectedLayers = new Array;
var ref = new ActionReference();
ref.putEnumerated( charIDToTypeID("Dcmn"), charIDToTypeID("Ordn"), charIDToTypeID("Trgt") );
var desc = executeActionGet(ref);
if( desc.hasKey( stringIDToTypeID( 'targetLayers' ) ) ){
desc = desc.getList( stringIDToTypeID( 'targetLayers' ));
var c = desc.count
var selectedLayers = new Array();
for(var i=0;i<c;i++){
try{
activeDocument.backgroundLayer;
selectedLayers.push( desc.getReference( i ).getIndex() );
}catch(e){
selectedLayers.push( desc.getReference( i ).getIndex()+1 );
}
}
}else{
var ref = new ActionReference();
ref.putProperty( charIDToTypeID("Prpr") , charIDToTypeID( "ItmI" ));
ref.putEnumerated( charIDToTypeID("Lyr "), charIDToTypeID("Ordn"), charIDToTypeID("Trgt") );
try{
activeDocument.backgroundLayer;
selectedLayers.push( executeActionGet(ref).getInteger(charIDToTypeID( "ItmI" ))-1);
}catch(e){
selectedLayers.push( executeActionGet(ref).getInteger(charIDToTypeID( "ItmI" )));
}
}
return selectedLayers;
};
function selectAllLayers() {
var desc29 = new ActionDescriptor();
var ref23 = new ActionReference();
ref23.putEnumerated( charIDToTypeID('Lyr '), charIDToTypeID('Ordn'), charIDToTypeID('Trgt') );
desc29.putReference( charIDToTypeID('null'), ref23 );
executeAction( stringIDToTypeID('selectAllLayers'), desc29, DialogModes.NO );
};
function layerName(idx){
var ref = new ActionReference();
ref.putIndex( charIDToTypeID( "Lyr " ), idx);
var desc = executeActionGet(ref);
return desc.getString(stringIDToTypeID("name"));
};
function selectLayerByIndex(index,add){
add = undefined ? add = false:add
var ref = new ActionReference();
ref.putIndex(charIDToTypeID("Lyr "), index);
var desc = new ActionDescriptor();
desc.putReference(charIDToTypeID("null"), ref );
if(add) desc.putEnumerated( stringIDToTypeID( "selectionModifier" ), stringIDToTypeID( "selectionModifierType" ), stringIDToTypeID( "addToSelection" ) );
desc.putBoolean( charIDToTypeID( "MkVs" ), false );
try{
executeAction(charIDToTypeID("slct"), desc, DialogModes.NO );
}catch(e){
alert(e.message);
}
};
BUT, there is one problem, my files have a ton of layers and so it appears that this code must iterate through them all, as such each time i need to run this script it takes 7minutes to execute. Is there a way to optimize this such that it will be faster even in files with VERY HIGH layer counts? Thanks
Each Photoshop layer is given a unique ID - (generated at creation in numerical order - I think - don't quote me on that) So you can access each layer by the ID instead of layer.getByname. The code below will show you the ID of the currently selected layer. - The upshot being, if you know the ID, you can get by layerID. :)
To select more than one layer at a time: reuse the select_layer_by_ID with layer and true to add to the current selection.
Get layer by ID:
// Switch off any dialog boxes
displayDialogs = DialogModes.NO; // OFF
var srcDoc = app.activeDocument;
var theLayer = srcDoc.activeLayer;
var myLayerID = get_layer_id(theLayer);
srcDoc.activeLayer = srcDoc.layers[0]; //top layer
// now go back to original layer via layer ID!
// select by layer ID
select_layer_by_ID(myLayerID);
alert("Layer ID: " + myLayerID + "\n" + srcDoc.activeLayer.name);
// Switch off any dialog boxes
displayDialogs = DialogModes.ALL; // ON
// function SELECT LAYER BY ID(int, boolean)
// --------------------------------------------------------
function select_layer_by_ID(id, add)
{
if (add == undefined) add = false;
var desc1 = new ActionDescriptor();
var ref1 = new ActionReference();
ref1.putIdentifier(charIDToTypeID('Lyr '), id);
desc1.putReference(charIDToTypeID('null'), ref1);
if (add) desc1.putEnumerated(stringIDToTypeID("selectionModifier"), stringIDToTypeID("selectionModifierType"), stringIDToTypeID("addToSelection"));
executeAction(charIDToTypeID('slct'), desc1, DialogModes.NO);
}
// function GET LAYER ID(obj)
// --------------------------------------------------------
function get_layer_id(alayer)
{
return alayer.id;
}

Script to make 1 random layer visible within each group [Photoshop cc2018]

I'm trying to make a script that would at random select and show a single layer from all groups on Photoshop and export the result as a png.
I found this script here that seems to work:
function Visible() {
var Grps = app.activeDocument.layerSets; // loops through all groups
for(var i = 0; i < Grps.length; i++){
var tmp = app.activeDocument.layerSets[i].layers.length;
app.activeDocument.layerSets[i].visible=true;
var groupChildArr = app.activeDocument.layerSets[i].layers;
var randLays = Math.floor(Math.random() * tmp);
groupChildArr[randLays].visible = true;
Save();
}
Revert();
}
function Save() {
var outFolder = app.activeDocument; // psd name
var outPath = outFolder.path;
var fName = "PNG"; // define folder name
var f = new Folder(outPath + "/" + fName);
if ( ! f.exists ) {
f.create()
}
var saveFile = new File(outPath + "/" + fName +"/" + "Pattern_" + num + ".png");
pngSaveOptions = new PNGSaveOptions();
pngSaveOptions.interlaced = false;
app.activeDocument.saveAs(saveFile, pngSaveOptions, true, Extension.LOWERCASE);
}
function Revert(){
var idslct = charIDToTypeID( "slct" );
var desc300 = new ActionDescriptor();
var idnull = charIDToTypeID( "null" );
var ref163 = new ActionReference();
var idSnpS = charIDToTypeID( "SnpS" );
ref163.putName( idSnpS, "test.psd" );
desc300.putReference( idnull, ref163 );
executeAction( idslct, desc300, DialogModes.NO );
}
var count = prompt("How many patterns you want","");
for (var x=0 ; x<count;x++){
var num = x+1;
Visible();
}
Share
Except it gives me an error 8800: General Photoshop error occurred. This functionality may not be available in this version of Photoshop.
Line: 36
-> executeAction( idslct, desc300, DialogModes.NO );
Is there smth I can do to make it work as that would greatly help speed up my work process.
Thank you.
Without seeing what your PSD looks like, it's hard to tell. However, I think the code is failing on the revert function.
Try this instead:
function Revert()
{
// =======================================================
var idRvrt = charIDToTypeID( "Rvrt" );
executeAction( idRvrt, undefined, DialogModes.NO );
}

return folder path illustrator jsx different result in illustrat CC2018 to 2021

I have a couple of long-standing scripts that have worked well over the last few years. However when I run the script in newer versions of (illustrator 2019 onward) the exact same piece of code returns differing results, which is causing the script to fail. This is the code that's causing the issues:
var doc = app.activeDocument;//Gets the active document
var fileName = doc.name.slice(0, 9);//Gets the G Number
$.writeln('thisfile ', fileName)
var numArtboards = doc.artboards.length;//returns the number of artboards in the document
var folderPath = (doc.fullName.parent.fsName.replace(/\\/g, '/'))
$.writeln('folderPath ', folderPath)
In illustrator CC 2018 the output console returns the following:
thisfile G0037_21X
folderPath /Users/bobhaslett/Documents/MF1/2021/01 January 2021/13:01:2021
This is what I expect and works with the rest of the script. However, if I try to run this same code using Illustrator 2021 get the following error:
Starting /Users/bobhaslett/Documents/MF1/2021/01 January 2021/13:01:2021/ExportArtboards/ExportArtboards v0.1.4.jsx in target: illustrator-25.064 and engine: main.
Runtime Error: Error Code# 21: null is not an object # file '~/Documents/MF1/2021/01%20January%202021/13:01:2021/ExportArtboards/ExportArtboards%20v0.1.4.jsx' [line:7, col:1]
I really stuck here and would appreciate any help
Thanks
Here is the full script as requested
//Version 0.1.4
var doc = app.activeDocument;//Gets the active document
var fileName = doc.name.slice(0, 9);//Gets the G Number
$.writeln('thisfile ', fileName)
var numArtboards = doc.artboards.length;//returns the number of artboards in the document
var folderPath = (doc.fullName.parent.fsName.replace(/\\/g, '/'))
$.writeln('folderPath ', folderPath)
//var folderPath = (app.activeDocument.fullName.parent.fsName).toString().replace(/\\/g, '/');
var options = new ImageCaptureOptions();
var filePath = folderPath + "/ImageSet";
$.writeln(filePath)
var folder = new Folder(filePath);
if (!folder.exists) {
folder.create()
}
//Loop through every item on the page checking for text frames
for (var i = 0; i < doc.pageItems.length; i++) {
var item = doc.pageItems[i];
if (item.constructor.name == "TextFrame") {
try {
checkText(item);
}
catch (e) { }
}
}
//Checks text for smart puctuation
function checkText(item) {
//var txt = item.contents.replace("“", "‘");
var txt = item.contents.replace(/n't/g, "n’t")
item.contents = txt;
var txt = item.contents.replace(/'r/g, "’r")
item.contents = txt;
var txt = item.contents.replace(/'d/g, "’d")
item.contents = txt;
var txt = item.contents.replace(/'l/g, "’l")
item.contents = txt;
var txt = item.contents.replace(/'s/g, "’s")
item.contents = txt;
var txt = item.contents.replace(/'m/g, "’m")
item.contents = txt;
var txt = item.contents.replace(/s'/g, "s’")
item.contents = txt;
}
for (var i = 0; i < numArtboards; i++) {
doc.artboards.setActiveArtboardIndex(i);
var activeAB = doc.artboards[doc.artboards.getActiveArtboardIndex()];
options.artBoardClipping = true;
options.resolution = 150;
options.antiAliasing = true;
options.matte = false;
options.horizontalScale = 100;
options.verticalScale = 100;
options.transparency = true;
var artboardName = doc.artboards[i].name;
var destFile = new File(filePath + "/" + fileName + " " + artboardName + ".png");
doc.imageCapture(destFile, activeAB.artboardRect, options);
}

How to select a sublayer in Photoshop based on Javascript?

var docRef = app.activeDocument;
var layers = docRef.layers;
var myLayer = layers["组5"]; //this defines the layer that you want to get the selection from
var myLayer = app.activeDocument.layers["组5"];
//alert(myLayer.layers);
docRef.selection = null;//这句是让你没有选中任何图层
for (var i=0;i<myLayer.layers.length;i++){
if (myLayer.layers[i].name=="图层"){ // alert(myLayer.layers[i].name=="图层");
// alert(myLayer.layers[i].name);
myLayer.layers[i].selected=true;
}
}
I have code like this, when in photoshop cs , that some sublayers have names equal to "图层" , then this sublayer should be selected, but doesn't work, who knows how to get them selected?
To my knowledge this is not possible with DOM, but Action Manager code will do the job:
var myName = "Layer 5";
deselectLayers(); // deselecting all layers first
traverseAllLayers(myName);
function selectByID(id)
{
var desc = new ActionDescriptor();
var ref = new ActionReference();
ref.putIdentifier(charIDToTypeID('Lyr '), id);
desc.putReference(charIDToTypeID('null'), ref);
desc.putEnumerated(stringIDToTypeID("selectionModifier"), stringIDToTypeID("selectionModifierType"), stringIDToTypeID("addToSelection"));
executeAction(charIDToTypeID('slct'), desc, DialogModes.NO);
};
function deselectLayers()
{
var desc60 = new ActionDescriptor();
var ref30 = new ActionReference();
ref30.putEnumerated(charIDToTypeID('Lyr '), charIDToTypeID('Ordn'), charIDToTypeID('Trgt'));
desc60.putReference(charIDToTypeID('null'), ref30);
executeAction(stringIDToTypeID('selectNoLayers'), desc60, DialogModes.NO);
};
function traverseAllLayers(n)
{
var ref0 = new ActionReference();
ref0.putProperty(charIDToTypeID('Prpr'), stringIDToTypeID('numberOfLayers'));
ref0.putEnumerated(charIDToTypeID("Dcmn"), charIDToTypeID("Ordn"), charIDToTypeID("Trgt"));
var desc0 = executeActionGet(ref0);
var i = desc0.getInteger(stringIDToTypeID('numberOfLayers'));
for (i; i > 0; i--)
{
ref = new ActionReference();
ref.putIndex(charIDToTypeID('Lyr '), i);
var desc = executeActionGet(ref);
var layerName = desc.getString(charIDToTypeID('Nm '));
var Id = desc.getInteger(stringIDToTypeID( 'layerID' ));
if (layerName == n) selectByID(Id) // selecting by ID, adding to selection
}
}

How to fill path item with color

I'm trying to draw closed path and fill it with some collor. Here the code
startRulerUnits = app.preferences.rulerUnits
startTypeUnits = app.preferences.typeUnits
startDisplayDialogs = app.displayDialogs
//change settings
app.preferences.rulerUnits = Units.PIXELS
app.preferences.typeUnits = TypeUnits.PIXELS
app.displayDialogs = DialogModes.NO
var AD = activeDocument;
var bBox = new Array();
bBox[0] = 10;
bBox[1] = 10;
bBox[2] = 50;
bBox[3] = 10;
bBox[4] = 50;
bBox[5] = 50;
bBox[6] = 10;
bBox[7] = 50;
var line = new Array();
line[0] = new PathPointInfo;
line[0].kind = PointKind.CORNERPOINT;
line[0].anchor = [bBox[0],bBox[1]];
line[0].leftDirection = line[0].anchor;
line[0].rightDirection = line[0].anchor;
line[1] = new PathPointInfo;
line[1].kind = PointKind.CORNERPOINT;
line[1].anchor = [bBox[2],bBox[3]];
line[1].leftDirection = line[1].anchor;
line[1].rightDirection = line[1].anchor;
line[2] = new PathPointInfo;
line[2].kind = PointKind.CORNERPOINT;
line[2].anchor = [bBox[4],bBox[5]];
line[2].leftDirection = line[2].anchor;
line[2].rightDirection = line[2].anchor;
line[3] = new PathPointInfo;
line[3].kind = PointKind.CORNERPOINT;
line[3].anchor = [bBox[6],bBox[7]];
line[3].leftDirection = line[3].anchor;
line[3].rightDirection = line[3].anchor;
var lineSubPath= new Array();
lineSubPath[0] = new SubPathInfo();
lineSubPath[0].operation = ShapeOperation.SHAPEXOR;
lineSubPath[0].closed = true;
lineSubPath[0].entireSubPath = line;
var path = AD.pathItems.add("A", lineSubPath);
//var paperShape = AD.artLayers.add();
var colorRef = new SolidColor;
colorRef.rgb.red = 255
colorRef.rgb.green = 100;
colorRef.rgb.blue = 10;
path.fillPath(colorRef, ColorBlendMode.COLOR,100,true,0,true,true);
//shapeLayer.applyStyle("ransom_note");*/
app.preferences.rulerunits = startRulerUnits
app.preferences.typeunits = startTypeUnits
app.displayDialogs = startDisplayDialogs
path is drawn, but error apears while filling
fillPath is not a function.
Can anybody help?
P.S. Sorry for my English
path is a property of Application, Photoshop does not understand when you try to apply fillPath to it, even if you had declared it as a variable name... you just gets Photoshop confused on what to do.
You should simply change that's variable name to something like myPath and then myPath.fillPath(colorRef, ColorBlendMode.COLOR,100,true,0,true,true); will work.
I would also make a little change in the ColorBlendMode, if you set it to COLOR you won't be able to actually see the color you are applying, and it will seem that the script is not working at all.
Try myPath.fillPath(colorRef, ColorBlendMode.NORMAL,100,true,0,true,true); and you're done!

Categories

Resources