Search code examples
javascriptjsxphotoshopphotoshop-script

Javascript Auto Increment Code not working


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!

Image of the script result, 10 is not generated properly. As well as 1

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');
    }
};```

Solution

  • You could try it this way:

    for (var i=1; i <= numImages; i++) {
        var str = "" + i;
        var pad = "000";
        var ans = pad.substring(0, pad.length - str.length) + str;
        layer.textItem.contents = ans;
        SavePNG(directory + imageName + '_'+ ans +'.png');
      };

    You can change pad template as you wish. The output of this will be:

    1 -> 001

    97 -> 097

    999 -> 999

    1234 -> 1234