Skip to content

Instantly share code, notes, and snippets.

@spajus
Created January 7, 2019 17:48
Show Gist options
  • Save spajus/175d8f98948b5ff0233213f011280ba6 to your computer and use it in GitHub Desktop.
Save spajus/175d8f98948b5ff0233213f011280ba6 to your computer and use it in GitHub Desktop.
// Put this file in Program Files\Adobe\Photoshop\Presets\Scripts\
// In PhotoShop menu File > Scripts > Layers To Sprite Sheet
// Arrange layers into a sprite sheet.
if (documents.length > 0) {
var docRef = activeDocument;
var numLayers = docRef.artLayers.length;
var cols = docRef.width;
var spriteX = docRef.width;
var spriteY = docRef.height;
app.preferences.rulerUnits = Units.PIXELS;
var hasBackground = false;
var layerNumbers = [];
for (i = 0; i < numLayers; i++) {
if (docRef.artLayers[i].isBackgroundLayer) {
docRef.artLayers[i].visible = false;
hasBackground = true;
} else {
layerNumbers.push(i);
}
}
var numSprites = layerNumbers.length;
var rowSize = prompt("How many sprites per row?", "8", "Configure stylesheet");
var rowCount = Math.ceil(numSprites / rowSize);
var emptySpaces = (rowSize * rowCount) - numSprites;
while (rowSize && !confirm("Is " + rowSize + "x" + rowCount + " sheet OK? There will be " + emptySpaces + " empty spaces.")) {
rowSize = prompt("How many sprites per row?", "8", "Configure stylesheet");
rowCount = Math.ceil(numSprites / rowSize);
emptySpaces = (rowSize * rowCount) - numSprites;
}
if (rowSize) { // cannot return from function in photoshop :/
var reverse = confirm("Use reverse order? Photoshop creates new sprites on top, with reverse order first sprite will be the most bottom layer");
if (reverse) {
layerNumbers.reverse();
}
var newX = rowSize * spriteX;
var newY = rowCount * spriteY;
docRef.resizeCanvas(newX, newY, AnchorPosition.TOPLEFT);
var startOffset = hasBackground ? 2 : 1;
startOffset += emptySpaces;
for (i = 0; i < rowSize; i++) {
for (j = 0; j < rowCount; j++) {
var layer = rowSize * j + i;
if (layer >= numSprites) {
continue;
}
layer = layerNumbers[layer];
try {
if (docRef.artLayers[layer].isBackgroundLayer) {
docRef.artLayers[layer].visible = 0;
} else {
docRef.artLayers[layer].visible = 1;
var movX = spriteX * i;
var movY = spriteY * j
docRef.artLayers[layer].translate(movX, movY);
}
} catch (e) {
alert("Layer " + layer + " at row:col " + j + ":" + i + " failed: " + e.message);
}
}
}
}
}
@spajus
Copy link
Author

spajus commented Jan 7, 2019

@Julix91
Copy link

Julix91 commented Jun 23, 2020

I used it, worked well for me! :)

@mechaniac
Copy link

works perfectly!
thanks a lot!

@colorage
Copy link

The best version. Thanks

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment