Set layer active photoshop script - photoshop

So I have 2 open documents with the same layer names.
I want to select a layer in the first document. Then run the script and automaticly select the same layer by name in the other document.
So far i've bin able to store the first layer name and open the 2nd document.
But I can't seem to set the same layer active.
This is my code:
var aDoc = app.activeDocument;
var AllDocs = app.documents;
var actLay = aDoc.activeLayer;
if (AllDocs.length > 1) {
var itemDoc = null;
var win = new Window("dialog","select the same name in other document");
this.windowRef = win;
win.Txt1 = win.add ("statictext", undefined, "Paste in which open document?");
win.NewList=win.add ("dropdownlist", undefined, AllDocs);
win.NewList.selection = 0;
itemDoc = win.NewList.selection.index;
win.testBtn4 = win.add('button', [260,140,100,50], 'select the same name in other document', {name:'doding1'});
win.testBtn4.onClick = dothing;
//Get selected document from list
win.NewList.onChange= function () {
itemDoc = win.NewList.selection.index;
return itemDoc;
}
//Show al items
win.show();
function dothing()
{
//Make the selected document the active document.
app.activeDocument = app.documents[itemDoc];
app.refresh();
//This outputs [Artlayer layername]
//alert (actLay);
//Find right layer and set active THIS DOES NOT WORK!!
//app.activeDocument.activeLayer = app.activeDocument.layers.itemByName(actLay);
win.close();
}
}
else
{
alert ("No other documents open");
}

Figured it out! Because the layer was in a certain group it couldn't find the layer.
fixed it with the following code:
activeDocument.activeLayer = activeDocument.layerSets[groupname].artLayers.getByName (actLay);

I got this from the adobe forum.
Someone wrote a function to find the location of the layer more easily.
//usage example:
select_layer(actLay.name);
function select_layer(id, add, viz)
{
try {
var d = new ActionDescriptor();
if (viz == undefined) viz = false;
var r = new ActionReference();
if (typeof(id) == "string") r.putName( charIDToTypeID( "Lyr " ), id);
else r.putIdentifier( charIDToTypeID( "Lyr " ), id);
d.putReference( charIDToTypeID( "null" ), r );
d.putBoolean( charIDToTypeID( "MkVs" ), viz );
if (add == true) d.putEnumerated( stringIDToTypeID( "selectionModifier" ), stringIDToTypeID( "selectionModifierType" ), stringIDToTypeID( "addToSelection" ) );
if (add == -1) d.putEnumerated( stringIDToTypeID( "selectionModifier" ), stringIDToTypeID( "selectionModifierType" ), stringIDToTypeID( "removeFromSelection" ) );
var ok = true;
try { executeAction( charIDToTypeID( "slct" ), d, DialogModes.NO ); } catch(e) { ok = false; }
d = null;
return ok;
}
catch (e) { alert(e); return false; }
}

Related

Photoshop 2019 | Export layers composition to files with respect to arboards + add suffix from the name of layer comps

Is there any way or script to export layers composition to files with respect to artboards? I need the exported files to be named from artboards and suffix from the name of layer comps?
Thank you in advance, because I could not find a solution.
Here is your script. save it as any name.jsx and move it to your photoshops script Folder
It'll ask you for folder input and then will save it to appropriate folder with the name condition you said! Have fun :)
#target photoshop
var doc=app.activeDocument;
var artbrd=doc.layerSets;//return artboards as array
var lyrcmp=doc.layerComps;//return layercomps as array
var fldr = Folder.selectDialog ("Choose Save Location","");
var lyrcompname;
var artname;
for(var i=0;i<lyrcmp.length;i++){
var cmpname=lyrcmp[i].name;
lyrcompname = lyrcmp[i].name;
var idapplyComp = stringIDToTypeID( "applyComp" );
var desc353 = new ActionDescriptor();
var idnull = charIDToTypeID( "null" );
var ref75 = new ActionReference();
var idcompsClass = stringIDToTypeID( "compsClass" );
ref75.putName( idcompsClass, cmpname);
desc353.putReference( idnull, ref75 );
executeAction( idapplyComp, desc353, DialogModes.NO );
exportArtboard ();
}
function exportArtboard(){
for (var z=0;z<artbrd.length;z++){
artname=artbrd[z].name;
selectart();
cutpaste();
var saveFile = new File(fldr + "/" + artname + "_" + lyrcompname + ".jpg");
var saveOptions = new JPEGSaveOptions();
saveOptions.embedColorProfile = true;
saveOptions.formatOptions = FormatOptions.STANDARDBASELINE;
saveOptions.matte = MatteType.NONE;
saveOptions.quality = 10;
app.activeDocument.saveAs(saveFile, saveOptions, true, Extension.LOWERCASE);
app.activeDocument.close(SaveOptions.DONOTSAVECHANGES);
}
}
function cutpaste(){
cTID = function(s) { return app.charIDToTypeID(s); };
sTID = function(s) { return app.stringIDToTypeID(s); };
function Action2() {
// Set
function step1(enabled, withDialog) {
if (enabled != undefined && !enabled)
return;
var dialogMode = (withDialog ? DialogModes.ALL : DialogModes.NO);
var desc1 = new ActionDescriptor();
var ref1 = new ActionReference();
ref1.putProperty(cTID('Chnl'), sTID("selection"));
desc1.putReference(cTID('null'), ref1);
desc1.putEnumerated(cTID('T '), cTID('Ordn'), cTID('Al '));
executeAction(cTID('setd'), desc1, dialogMode);
};
// Copy Merged
function step2(enabled, withDialog) {
if (enabled != undefined && !enabled)
return;
var dialogMode = (withDialog ? DialogModes.ALL : DialogModes.NO);
executeAction(sTID('copyMerged'), undefined, dialogMode);
};
// Set
function step3(enabled, withDialog) {
if (enabled != undefined && !enabled)
return;
var dialogMode = (withDialog ? DialogModes.ALL : DialogModes.NO);
var desc1 = new ActionDescriptor();
var ref1 = new ActionReference();
ref1.putProperty(cTID('Chnl'), sTID("selection"));
desc1.putReference(cTID('null'), ref1);
desc1.putEnumerated(cTID('T '), cTID('Ordn'), cTID('None'));
executeAction(cTID('setd'), desc1, dialogMode);
};
// Make
function step4(enabled, withDialog) {
if (enabled != undefined && !enabled)
return;
var dialogMode = (withDialog ? DialogModes.ALL : DialogModes.NO);
var desc1 = new ActionDescriptor();
var desc2 = new ActionDescriptor();
desc2.putBoolean(sTID("artboard"), false);
desc2.putString(sTID("preset"), "Clipboard");
desc1.putObject(cTID('Nw '), cTID('Dcmn'), desc2);
desc1.putInteger(cTID('DocI'), 287);
executeAction(cTID('Mk '), desc1, dialogMode);
};
// Paste
function step5(enabled, withDialog) {
if (enabled != undefined && !enabled)
return;
var dialogMode = (withDialog ? DialogModes.ALL : DialogModes.NO);
var desc1 = new ActionDescriptor();
desc1.putEnumerated(cTID('AntA'), cTID('Annt'), cTID('Anno'));
desc1.putClass(cTID('As '), cTID('Pxel'));
executeAction(cTID('past'), desc1, dialogMode);
};
step1(); // Set
step2(); // Copy Merged
step3(); // Set
step4(); // Make
step5(); // Paste
};
Action2.main = function () {
Action2();
};
Action2.main();
}
function selectart(){
cTID = function(s) { return app.charIDToTypeID(s); };
sTID = function(s) { return app.stringIDToTypeID(s); };
function select() {
// Select
function step1(enabled, withDialog) {
if (enabled != undefined && !enabled)
return;
var dialogMode = (withDialog ? DialogModes.ALL : DialogModes.NO);
var desc1 = new ActionDescriptor();
var ref1 = new ActionReference();
ref1.putName(cTID('Lyr '), artname);
desc1.putReference(cTID('null'), ref1);
desc1.putBoolean(cTID('MkVs'), false);
var list1 = new ActionList();
list1.putInteger(8);
desc1.putList(cTID('LyrI'), list1);
executeAction(cTID('slct'), desc1, dialogMode);
};
step1(); // Select
};
select();
}

Photoshop script rename visible layer after file

could you help me with a Photoshop script that renames the visible layers after the file name ?
I have an insane number of PS files for which I have to do it.
Thanks, I appreciate it.
Like this for example:
function selectByID(id)
{
var desc = new ActionDescriptor();
var ref = new ActionReference();
ref.putIdentifier(charIDToTypeID('Lyr '), id);
desc.putReference(charIDToTypeID('null'), ref);
executeAction(charIDToTypeID('slct'), desc, DialogModes.NO);
};
function traverseAllLayers(n)
{
try
{
activeDocument.backgroundLayer;
var layers = 0
}
catch (e)
{
var layers = 1;
};
while (true)
{
ref = new ActionReference();
ref.putIndex(charIDToTypeID('Lyr '), layers);
try
{
var desc = executeActionGet(ref);
}
catch (err)
{
break;
}
if (desc.getBoolean(charIDToTypeID("Vsbl")) && desc.getInteger(stringIDToTypeID("layerKind")) != 13) {
var myId = desc.getInteger(stringIDToTypeID( 'layerID' ));
selectByID(myId);
activeDocument.activeLayer.name = activeDocument.name
}
layers++;
}
};
app.activeDocument.suspendHistory("temp", "traverseAllLayers()");

Image not resizing when added programmatically prestashop

I am abel to add image programmatically. But images are not getting resized. In other words resized images are not generating. Attaching the code I use:
$image = new Image();
$image_url = 'http://i.imgur.com/0zSw2gl.jpg';
$id_image = Product::getCover($id_product);
$shops = Shop::getShops(true, null, true);
$image->id_product = $id_product;
$image->position = Image::getHighestPosition($id_product) + 1;
$image->cover = true; // or false;
if (($image->validateFields(false, true)) === true &&
($image->validateFieldsLang(false, true)) === true && $image->add())
{
$image->associateTo($shops);
if (!AdminImportControllerExtended::copyImgCustom($id_product, $image->id, $image_url, 'products', false))
{
$image->delete();
}
}
Images should be resized programatically
I use this code
$image = new Image();
$image->id_product = (int)$product->id;
$image->position = Image::getHighestPosition($product->id) + 1;
$image->cover = 1;
if (!$image->add())
exit(Tools::jsonEncode(array('error' => Tools::displayError('Error while creating additional image'))));
else
{
$new_path = $image->getPathForCreation();
ImageManager::resize($image_path, $new_path.'.'.$image->image_format);
$images_types = ImageType::getImagesTypes('products');
foreach ($images_types as $image_type)
{
if (!ImageManager::resize($image_path, $new_path.'-'.Tools::stripslashes($image_type['name']).'.'.
$image->image_format, $image_type['width'], $image_type['height'], $image->image_format))
exit(Tools::jsonEncode(array('error' => Tools::displayError('An error occurred while copying image:').
' '.Tools::stripslashes($image_type['name']))));
}
$image->update();
}

Photoshop CS6 Export Nested Layers to PNG?

I have a PSD that contains 100s of layers. Most are grouped with individual elements within the groups (nested).
How do I Export to PNG certain individual groups (with nested layers inside of them)?
I don't want to run the Export All Layers to PNG Script, just need to export individual nested groups (layers) to PNG. I've found a few other 3rd party scripts, but they export everything. Only need to export the ones I've selected.
Thanks in advance
This script should do what you want. It works only when you have the group that you want selected (not a layer within that group) I've not extensively tested it and I'm assuming you don't have groups within groups (which becomes a headache)
// export png from group
srcDoc = app.activeDocument;
var allLayers = new Array();
var selectedLayer = srcDoc.activeLayer;
var theLayers = collectAllLayers(app.activeDocument, 0);
var groupName = "";
// function collect all layers
function collectAllLayers (theParent, level)
{
for (var m = theParent.layers.length - 1; m >= 0; m--)
{
var theLayer = theParent.layers[m];
// apply the function to layersets;
if (theLayer.typename == "LayerSet")
{
var goCode = false;
allLayers.push(level + theLayer.name);
groupName = theLayer.name
// alert(level + " " + theLayer.name)
collectAllLayers(theLayer, level + 1)
var subDoc = srcDoc.layers[m];
//alert(subDoc)
var numOfSubLayers = subDoc.layers.length;
//alert(numOfSubLayers)
for (var j = numOfSubLayers -1; j >= 0 ; j--)
{
if (subDoc.layers[j].typename == "ArtLayer")
{
// if the selected (active) layer is in the group
if (theLayer == selectedLayer)
{
var mylayerName = subDoc.layers[j].name
srcDoc.activeLayer = subDoc.layers[j];
// alert("Selected: " + mylayerName + " in " + groupName)
processLayer(mylayerName)
//selectAllLayersInGroup(groupName)
}
}
}
}
}
}
function processLayer(alayername)
{
// duplicate image into new document
// =======================================================
var id2784 = charIDToTypeID( "Mk " );
var desc707 = new ActionDescriptor();
var id2785 = charIDToTypeID( "null" );
var ref508 = new ActionReference();
var id2786 = charIDToTypeID( "Dcmn" );
ref508.putClass( id2786 );
desc707.putReference( id2785, ref508 );
var id2787 = charIDToTypeID( "Nm " );
desc707.putString( id2787, alayername );
var id2788 = charIDToTypeID( "Usng" );
var ref509 = new ActionReference();
var id2789 = charIDToTypeID( "Lyr " );
var id2790 = charIDToTypeID( "Ordn" );
var id2791 = charIDToTypeID( "Trgt" );
ref509.putEnumerated( id2789, id2790, id2791 );
desc707.putReference( id2788, ref509 );
executeAction( id2784, desc707, DialogModes.NO );
// create new layer
var layerRef = app.activeDocument.artLayers.add()
layerRef.name = "temp"
layerRef.blendMode = BlendMode.NORMAL
//merge visible
// =======================================================
var id1435 = charIDToTypeID( "MrgV" );
executeAction( id1435, undefined, DialogModes.NO );
// Set filePath and fileName to source path
filePath = srcDoc.path + '/' + app.activeDocument.name + '.png';
// save out the image
var pngFile = new File(filePath);
pngSaveOptions = new PNGSaveOptions();
pngSaveOptions.embedColorProfile = true;
pngSaveOptions.formatOptions = FormatOptions.STANDARDBASELINE;
pngSaveOptions.matte = MatteType.NONE; pngSaveOptions.quality = 1;
activeDocument.saveAs(pngFile, pngSaveOptions, false, Extension.LOWERCASE);
// alert(filePath)
// close that save png
app.activeDocument.close()
// selects document that's been open the longest
app.activeDocument = srcDoc;
}

how to to process result of google distance matrix api further?

i am new to programming.. i have this code which gives distance between two points but need to further multiply it by an integer say 10.. the project i am working on is abt calculating distance between two points and multiplying it with fare/Km like Rs.10/km (Indian Rupees) for the same. So if the distance is 30 km the fare would be 30*10 = Rs.300
Thanks in advance
following is the code
<script>
var map;
var geocoder;
var bounds = new google.maps.LatLngBounds();
var markersArray = [];
var origin1 = '';
var destinationA = '';
var destinationIcon = 'https://chart.googleapis.com/chart?chst=d_map_pin_letter&chld=D|FF0000|000000';
var originIcon = 'https://chart.googleapis.com/chart?chst=d_map_pin_letter&chld=O|FFFF00|000000';
function initialize() {
var opts = {
center: new google.maps.LatLng(55.53, 9.4),
zoom: 10,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById('map'), opts);
var fromText = document.getElementById('FAdd');
var options = {
componentRestrictions: {country: 'in'}
};var fromAuto = new google.maps.places.Autocomplete(fromText, options);
fromAuto.bindTo('bound', map);
var toText = document.getElementById('TAdd');
var toAuto = new google.maps.places.Autocomplete(toText, options);
toAuto.bindTo('bound', map);
geocoder = new google.maps.Geocoder();
}
function calculateDistances() {
var service = new google.maps.DistanceMatrixService();
service.getDistanceMatrix(
{
origins: [document.getElementById("FAdd").value],
destinations: [document.getElementById("TAdd").value],
travelMode: google.maps.TravelMode.DRIVING,
unitSystem: google.maps.UnitSystem.METRIC,
avoidHighways: false,
avoidTolls: false
}, callback);
}
function callback(response, status) {
if (status != google.maps.DistanceMatrixStatus.OK) {
alert('Error was: ' + status);
} else {
var origins = response.originAddresses;
var destinations = response.destinationAddresses;
var outputDiv = document.getElementById('outputDiv');
outputDiv.innerHTML = '';
deleteOverlays();
for (var i = 0; i < origins.length; i++) {
var results = response.rows[i].elements;
addMarker(origins[i], false);
for (var j = 0; j < results.length; j++) {
addMarker(destinations[j], true);
outputDiv.innerHTML += results[j].distance.text + '<br>';
}
}
}
}
function addMarker(location, isDestination) {
var icon;
if (isDestination) {
icon = destinationIcon;
} else {
icon = originIcon;
}
geocoder.geocode({'address': location}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
bounds.extend(results[0].geometry.location);
map.fitBounds(bounds);
var marker = new google.maps.Marker({
map: map,
position: results[0].geometry.location,
icon: icon
});
markersArray.push(marker);
} else {
alert('Geocode was not successful for the following reason: '
+ status);
}
});
}
function deleteOverlays() {
if (markersArray) {
for (i in markersArray) {
markersArray[i].setMap(null);
}
markersArray.length = 0;
}
}
</script>
I use an Ajax call to PHP, and haven't yet used getDistanceMatrix(), but this should be an easy fix.
First, if you know you will always only have one origin and one destination, you don't need the "for" loop in your callback function. Second, you're taking the distance text rather than the distance value.
function callback(response, status) {
if (status != google.maps.DistanceMatrixStatus.OK) {
[...]
} else {
deleteOverlays();
var outputDiv = document.getElementById('outputDiv'),
origin = response.originAddresses[0],
destination = response.destinationAddresses[0],
result = response.rows[0].elements[0],
distance = result.distance.value,
text = result.distance.text,
price = 10 * distance;
outputDiv.innerHTML = '<p>' + text + ': Rs.' + price + '</p>';
addMarker(origin, false);
addMarker(destination, false);
}
}
I haven't tested this, so it probably needs to be tweaked. ( See https://developers.google.com/maps/documentation/distancematrix/#DistanceMatrixResponses )