Skip to content

Instantly share code, notes, and snippets.

@bebensiganteng
Last active May 18, 2016 09:22
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save bebensiganteng/6182956 to your computer and use it in GitHub Desktop.
Save bebensiganteng/6182956 to your computer and use it in GitHub Desktop.
Photoshop script for retrieving object's positions and saving it to JSON
#target photoshop
/*--------------------------------------------------------
Config
-------------------------------------------------------*/
var originalRulerUnits = preferences.rulerUnits;
preferences.rulerUnits = Units.PIXELS;
/*--------------------------------------------------------
Functions
-------------------------------------------------------*/
function doCheck() {
if(!documents.length) {
alert('There are no documents open.');
return;
}
}
function traverseLayer(layers) {
for(var i = 0; i < layers.length; i++) {
var typename = layers[i].typename;
if(typename == "ArtLayer" || typename == "LayerSet") {
getLayerAttribute (layers[i]);
}
}
}
function getLayerAttribute(layer) {
var name = layer.name.split(".");
if(name[1] == "png" || name[1] == "jpg") {
if(firstRead < 1) {
jsonStr += "\n\t\t"
} else {
jsonStr += ",\n\t\t"
}
firstRead = 1;
jsonStr += '"' +name[0] + '": {\n';
jsonStr += '\t\t\t"x": ' + layer.bounds[0].value + ',\n';
jsonStr += '\t\t\t"y": ' + layer.bounds[1].value + ',\n';
jsonStr += '\t\t\t"width": ' + layer.bounds[2].value + ',\n';
jsonStr += '\t\t\t"height": ' + layer.bounds[3].value + '\n';
jsonStr += '\t\t}';
} else {
if(layer.layers.length > 0) {
traverseLayer(layer.layers);
}
}
}
/*--------------------------------------------------------
Start
--------------------------------------------------------*/
var doc = app.activeDocument;
var docWidth = doc.width.value;
var docHeight = doc.height.value;
var docFilePath = doc.fullName.path + "/";
var docFileName = doc.name.match(/([^\.]+)/)[1];
var firstRead = 0;
var jsonFileName = docFilePath.toString().match(/([^\.]+)/)[1] + "../json/" + docFileName + ".json";
var jsonStr = "{\n";
jsonStr += '\t"' + docFileName + '": {';
doCheck();
traverseLayer (doc.layers);
// create a reference to a file for output
var csvFile = new File(jsonFileName);
// open the file, write the data, then close the file
csvFile.open('w');
csvFile.writeln(jsonStr + "\n\t}\n}");
csvFile.close();
preferences.rulerUnits = originalRulerUnits;
// Confirm that operation has completed
alert("JSON Complete!\n" + jsonFileName);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment