Last active
July 14, 2016 18:43
-
-
Save caiodv/90754242d44d8855e642433d4da7b582 to your computer and use it in GitHub Desktop.
Generate a spritesheet from psd layers and export positions + size for css. must select all layers first, align them all together and trim the image, then run the script
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Save this file in Program Files\Adobe\Photoshop\Presets\Scripts\ | |
// In PhotoShop CS5, run it by going menu File > SCripts > Browse > layersToSprite.js | |
if (documents.length > 0) { | |
// Adjust this to the number of columns you want | |
//leave -1 if you want it to calculate an optimal column value. | |
var doc = app.activeDocument; | |
var cols = -1; | |
var docRef = activeDocument; | |
var numLayers = docRef.artLayers.length; | |
if (cols < 0) { | |
var sqrt = Math.floor( Math.sqrt(numLayers)); | |
if (Math.sqrt(numLayers) % sqrt == 0) { | |
cols = sqrt; | |
}else { | |
for (i = sqrt+1; i <= numLayers ; i++){ | |
if (numLayers % i == 0) { | |
cols = i; | |
break; | |
} | |
} | |
} | |
if (cols < 0) { | |
cols = numLayers; | |
} | |
} | |
var rows = Math.ceil(numLayers/cols); | |
var spriteX = docRef.width; | |
var spriteY = docRef.height; | |
// resize the canvas | |
app.preferences.rulerUnits = Units.PIXELS; | |
var newX = spriteX * cols; | |
var newY = spriteY * rows; | |
docRef.resizeCanvas( newX, newY, AnchorPosition.TOPLEFT ); | |
// move the layers to their their grid position | |
var rowi = 0; | |
var coli = 0; | |
var positions = ''; | |
for (i=(numLayers - 1); i >= 0; i--) | |
{ | |
docRef.artLayers[i].visible = 1; | |
var movX = spriteX*coli; | |
var movY = spriteY*rowi; | |
docRef.artLayers[i].translate(movX, movY); | |
positions += docRef.artLayers[i].name; | |
positions += 'x: -' + docRef.artLayers[i].bounds[0]; //x | |
positions += 'y: -' + docRef.artLayers[i].bounds[1]; //y | |
var w = docRef.artLayers[i].bounds[2] - docRef.artLayers[i].bounds[0]; // width | |
positions += 'width: ' + w; | |
var h = docRef.artLayers[i].bounds[3] - docRef.artLayers[i].bounds[1]; // height | |
positions += 'height:' + h; | |
positions += '------------' | |
coli++; | |
if (coli > (cols - 1)) | |
{ | |
rowi++; | |
coli = 0; | |
} | |
} | |
// savefile | |
var name = decodeURI(doc.name); | |
name = name.substring(0, name.indexOf(".")); | |
var file = new File(doc.path.toString() + "/" + name + ".json"); | |
file.remove(); | |
file.open("w", "TEXT"); | |
file.lineFeed = "\n"; | |
file.write(positions); | |
file.close(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Base file from: http://alessandroituarte.com/files/LayersToSpriteSheet.js