Skip to main content
Participant
April 23, 2023
Question

Trying to write a photoshop script to read csv variables

  • April 23, 2023
  • 1 reply
  • 679 views
 

I need corrections on this photoshop script.

 

I can open the csv file but it cant swap out the images on the layers with the images (i used the path) on the csv file.

 

The csv contains 5 columns wiht image path files

 

It can be achieved without script by using photoshop variables but i want to swap out lots of files and cant go back and forth clicking and repeating task.

 

 

`// Open the CSV file and parse its content
var csvFile = File.openDialog("Select CSV file", "*.csv");
csvFile.open("r");
var csvContent = csvFile.read();
csvFile.close();
var csvData = csvContent.split("\n");

// Loop through the CSV data and replace images on each layer in Photoshop
for (var i = 1; i < csvData.length; i++) {
  var rowData = csvData[i].split(",");
  
  // Open the image file
  var imageFile = new File(rowData[0]);
  var docRef = app.open(imageFile);
  
  // Loop through each layer and replace the image
  for (var j = 1; j <= docRef.layers.length; j++) {
    var layer = docRef.layers[j - 1];
    
    // Check if the layer is a image layer
    if (layer.kind == LayerKind.NORMAL && layer.bounds.toString() != "[0,0,0,0]") {
      
      // Replace the image layer with the new image file
      var imageFilePath = rowData[j];
      var newLayer = docRef.artLayers.add();
      newLayer.move(layer, ElementPlacement.PLACEBEFORE);
      newLayer.name = layer.name;`your text`
      newLayer.kind = LayerKind.NORMAL;
      var imageFileRef = new File(imageFilePath);
      app.activeDocument.activeLayer = newLayer;
      app.load(new File(imageFilePath));
      docRef.selection.selectAll();
      docRef.selection.copy();
      docRef.selection.deselect();
      app.activeDocument.paste();
      layer.remove();
    }
  }

  // Save the modified image file
  var saveOptions = new JPEGSaveOptions();
  saveOptions.quality = 12;
  var newFilePath = rowData[0].replace(".jpg", "_modified.jpg");
  docRef.saveAs(new File(newFilePath), saveOptions, true, Extension.LOWERCASE);
  docRef.close(SaveOptions.DONOTSAVECHANGES);
}

alert("Done!");`

 

This topic has been closed for replies.

1 reply

c.pfaffenbichler
Community Expert
Community Expert
April 25, 2023

What is the problem exactly? 

 

What is 

      app.load(new File(imageFilePath));

sopposed to do? Did you mean app.open? 

You don’t seem to switch the focus back to the original image before pasting. 

 

But … open/copy/paste seem like a waste of resources. 

Why don’t you place the image as a Smart Object (or replace contents if the Layer is a Smart Object already)? 

 

Please provide the layered image and one or two sets of replacement images and the corresponding csv-file.