Skip to content

Instantly share code, notes, and snippets.

@ChrisAntaki
Last active November 23, 2017 10:04
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save ChrisAntaki/0ea4059ece46fb069523 to your computer and use it in GitHub Desktop.
Save ChrisAntaki/0ea4059ece46fb069523 to your computer and use it in GitHub Desktop.
Photoshop: Layers To Sprite Sheet
// Notes:
// 1. Save this file in Program Files\Adobe\Photoshop\Presets\Scripts\
// 2. Run the script by going to menu File > Scripts > LayersToSpriteSheet
// Based on http://alessandroituarte.com/blag/2012/07/03/470
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 cols = -1;
for (var i = activeDocument.artLayers.length - 1; i > -1; i--) {
if (activeDocument.artLayers[i].isBackgroundLayer) {
activeDocument.artLayers[i].remove();
}
}
var numLayers = activeDocument.artLayers.length;
if (cols < 0) {
var sqrt = Math.floor(Math.sqrt(numLayers));
if (Math.sqrt(numLayers) % sqrt == 0) {
cols = sqrt;
} else {
for (var 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 = activeDocument.width;
var spriteY = activeDocument.height;
// resize the canvas
app.preferences.rulerUnits = Units.PIXELS;
var newX = spriteX * cols;
var newY = spriteY * rows;
activeDocument.resizeCanvas(newX, newY, AnchorPosition.TOPLEFT);
// move the layers to their their grid position
var rowi = 0;
var coli = 0;
for (var i = (numLayers - 1); i >= 0; i--) {
activeDocument.artLayers[i].visible = 1;
var movX = spriteX * coli;
var movY = spriteY * rowi;
activeDocument.artLayers[i].translate(movX, movY);
coli++;
if (coli > (cols - 1)) {
rowi++;
coli = 0;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment