I need to generate 1000 images each with different numbers. Doing this is found a script online which works fine, but it doesn’t work with 00 in front of the increments.
I can’t just add 00 in front of every number because when it hits 10 it’s doing 0010 instead of 010 like I want it to.
That means I need to change the code a bit. And it’s probably REALLY basic, but I just can’t figure it out. There is no log sadly, because I am running the script in Photoshop.
Here is the code I have trouble with. And underneath is the result:
for (var i=1; i <= numImages; i++) {
if(layer.textItem.contents < 10) {
layer.textItem.contents = "00" + i.toString();
} else if(layer.textItem.contents >= 10) {
layer.textItem.contents = "0" + i.toString();
} else {
layer.textItem.contents = i.toString();
}
SavePNG(directory + imageName + '_'+ i +'.png');
};
Any assistance is highly appreciated! I don’t need to be fed by a spoon! I need to learn from my mistakes!
Here is the entire code in the script (Forgot to add this, edited afterwards)
var imageName = 'Oppmoteskjema';
var numImages = 15;
function SavePNG(saveFile){
var pngOpts = new ExportOptionsSaveForWeb;
pngOpts.format = SaveDocumentType.PNG
pngOpts.PNG8 = false;
pngOpts.transparency = false;
pngOpts.interlaced = false;
pngOpts.quality = 10;
activeDocument.exportDocument(new File(saveFile),ExportType.SAVEFORWEB,pngOpts);
}
var layer = activeDocument.layers[0];
if (layer.kind == 'LayerKind.TEXT') {
for (var i=1; i <= numImages; i++) {
layer.textItem.contents = i.toString();
var str = "" + i;
var pad = "000";
var ans = pad.substring(0, pad.length - str.length) + str;
SavePNG(directory + imageName + '_'+ ans +'.png');
}
};```
3
Answers
You can add the number to a string of zeroes, and then slice the resulting string based on desired length:
You could try it this way:
You can change pad template as you wish. The output of this will be:
1 -> 001
97 -> 097
999 -> 999
1234 -> 1234
If you’re just trying to manipulate a variable based off the index of the loop then the below would suffice.
This
i < 10 ? '00' : i < 100 ? '0' : ''
Is a ternary operator btw, it’s essentially a shorthand if statement.