Skip to main content
Inspiring
March 15, 2023
Answered

Adding Meta keywords to jpg images

  • March 15, 2023
  • 6 replies
  • 9626 views

Hi Everyone, 

I am trying to add keywords to multiple jpg images in a folder. But each jpeg file will have different keywords. Here's the script I wrote, but it's not working as I wanted. Could you please help modify it? 

 

//Check if ExternalObject.AdobeXMPScript is available, and if not, create it
if (!ExternalObject.AdobeXMPScript) ExternalObject.AdobeXMPScript = new ExternalObject("lib:AdobeXMPScript");

// prompt the user to select the folder that contains the images to modify
var folderPath = Folder.selectDialog("Select the folder that contains the images you want to modify");

if (folderPath) { // check if a folder was selected
  // prompt the user to enter the keywords to add
  var keywords = prompt("Enter the keywords you want to add to the metadata, separated by commas:");

  if (keywords) { // check if the user entered keywords
    // get an array of all the files in the folder
    var folder = new Folder(folderPath);
    var files = folder.getFiles();

    // loop through each file in the folder
    for (var i = 0; i < files.length; i++) {
      // open the file
      var file = files[i];
      var doc = app.open(file);

      // add the desired keywords to the metadata
      var xmp = new XMPMeta(app.activeDocument.xmpMetadata.rawData);
      var subjectArray = xmp.getProperty(XMPConst.NS_DC, "subject");
      if (subjectArray == null) {
        subjectArray = new Array();
      }

      var newKeywords = keywords.split(","); // split the keywords into an array
      for (var j = 0; j < newKeywords.length; j++) {
        var keyword = newKeywords[j].trim(); // trim leading and trailing whitespace
        subjectArray[subjectArray.length] = keyword; // add the keyword to the subject array
      }

      // save the metadata to the file
      var xmpAsString = xmp.serialize(); // convert the XMPMeta object to a string
      app.activeDocument.info.xmpMetadata = xmpAsString; // set the metadata of the active document
      doc.close(SaveOptions.SAVECHANGES);
    }

    // display a message when the script is finished
    alert("Metadata update complete.");
  }
}

 

Two points to be noted. The jpegs are not looping. And keywords are not getting saved in the jpeg after running the script. Kindly help. 

Also would be great if the predefined keywords appear as a checkbox rather than the user entering it. Thanks in advance

This topic has been closed for replies.
Correct answer c.pfaffenbichler

Hey @c.pfaffenbichler Thanks for the quick response. Yes, it works perfectly for multiple keywords when separated by commas. But it takes one prompt and puts the keywords for all the images in the folder. But I would like to have the prompt for every jpeg. Here's how I modified the script you shared. This also allows us to preview the image while adding the keywords. I tried putting the preview inside the prompt but couldn't achieve it. 

 

@Stephen Marsh Please let me know your thoughts as well. Thanks. 

 

// prompt the user to select the folder that contains the images to modify
var folderPath = Folder.selectDialog("Select the folder that contains the images you want to modify");

if (folderPath) { // check if a folder was selected
  // get an array of all the files in the folder
  var folder = new Folder(folderPath);
  var files = folder.getFiles(/\.(jpg|jpeg)$/i);

  // loop through each file in the folder
  for (var i = 0; i < files.length; i++) {
    // open the file
    var file = files[i];
    var doc = open(file);
    
    // prompt the user to enter the keywords to add
    var keywords = prompt("Enter the keywords you want to add to the metadata for " + file.name + ", separated by commas:");

    if (keywords) { // check if the user entered keywords
      // add the desired keywords to the metadata
      setSubject( file, keywords );
    }

    // close the document
    doc.close(SaveOptions.DONOTSAVECHANGES);
  }

  // display a message when the script is finished
  alert("Metadata update complete.");
};

////// by paul riggott //////
function setSubject( file, descStr ){
  if ( !ExternalObject.AdobeXMPScript ) ExternalObject.AdobeXMPScript = new ExternalObject('lib:AdobeXMPScript');
          var xmpf = new XMPFile( File(file).fsName, XMPConst.UNKNOWN, XMPConst.OPEN_FOR_UPDATE );
          var xmp = xmpf.getXMP();
          xmp.deleteProperty(XMPConst.NS_DC, "subject");
          xmp.setLocalizedText( XMPConst.NS_DC, "subject", null, "x-default", descStr );
        if (xmpf.canPutXMP( xmp )) {
           xmpf.putXMP( xmp );
        }
        xmpf.closeFile( XMPConst.CLOSE_UPDATE_SAFELY );
};

 


@Vibi Dev , please try this: 

// prompt the user to select the folder that contains the images to modify
var folderPath = Folder.selectDialog("Select the folder that contains the images you want to modify");

if (folderPath) { // check if a folder was selected
  // get an array of all the files in the folder
  var folder = new Folder(folderPath);
  var files = folder.getFiles(/\.(jpg|jpeg)$/i);

  // loop through each file in the folder
  for (var i = 0; i < files.length; i++) {
    // open the file
    var file = files[i];
    
    // prompt the user to enter the keywords to add
    var keywords = prompt("Enter the keywords you want to add to the metadata for " + file.name + ", separated by commas:");

    if (keywords) { // check if the user entered keywords
      // add the desired keywords to the metadata
      var theKeywords = getSubject (File(file));
      if (theKeywords) {
          var theArray = theKeywords;
          theNew = keywords.split(",");
          for (var x = 0; x < theNew.length; x++) {
              var theCheck = true;
              var thisOne = theNew[x];
              for (var y = 0; y < theArray.length; y++) {
                  if (thisOne == theArray[y]) {theCheck = false}
              };
              if (theCheck == true) {theArray.push(thisOne)}
          }
      }
      else {var theArray = keywords.split(",")};
      setSubject( file, theArray );
    }

  }

  // display a message when the script is finished
  alert("Metadata update complete.");
};
////// get keywords, based on code by jazz-y //////
function getSubject (theFile) {
    try {
    //    var f = File.openDialog('Open file');
        if (!ExternalObject.AdobeXMPScript)ExternalObject.AdobeXMPScript = new ExternalObject('lib:AdobeXMPScript')
            var xmpFile = new XMPFile(File(theFile).fsName, XMPConst.UNKNOWN, XMPConst.OPEN_FOR_READ),
            xmp = xmpFile.getXMP();
        if (xmp.doesPropertyExist(XMPConst.NS_DC, 'subject')) {
            var i = xmp.iterator(XMPConst.ITERATOR_JUST_LEAFNODES, XMPConst.NS_DC, 'subject'),
                output = [];
            while (true) {
                var subject = i.next();
                if (subject) { output.push(subject.value) }
                else { break; }
            }
            return output
        }
    } catch (e) {};
};
////// based on code by paul riggott //////
function setSubject( file, anArray ){
    if ( !ExternalObject.AdobeXMPScript ) ExternalObject.AdobeXMPScript = new ExternalObject('lib:AdobeXMPScript');
        var xmpf = new XMPFile( File(file).fsName, XMPConst.UNKNOWN, XMPConst.OPEN_FOR_UPDATE );
        var xmp = xmpf.getXMP();
        xmp.deleteProperty(XMPConst.NS_DC, "subject");
        for(var s in anArray){
        xmp.appendArrayItem(XMPConst.NS_DC, "subject", anArray[s], 0,XMPConst.PROP_IS_ARRAY);
        };
    if (xmpf.canPutXMP( xmp )) {
        xmpf.putXMP( xmp );
    }
    xmpf.closeFile( XMPConst.CLOSE_UPDATE_SAFELY );
};

6 replies

c.pfaffenbichler
Community Expert
Community Expert
May 6, 2023

Please explain what your exact problem is. 

And please don’t post unrelated links lest you be suspected of spamming, 

www.Sochi.OOO
Participant
May 6, 2023

I use data METAPHORS only for the internet in order to save image weight. Is there any rule for entering META information for the purpose of photo search results?
After all, by prescribing all the fields of file information, we significantly make the image heavy.

Rest of Sochi https://www.sochi.ooo sector
www.DomSdan.com
Participant
May 6, 2023

Я тут сдаю гостевые дома в Сочи, но таких мероприятий в Фотошоп не делаю!

Гостевые Дома Сочи https://www.domsdan.com/ !
Participant
May 6, 2023

Оказывая услуги клининга в Сочи, мы сбрасываем изображения выполненных работ. Надо ли в них прописывать МЕТА-данные?

https://www.cleaningsochi.com/ !
Legend
March 17, 2023

If you are opening the files anyway, why not use the File Info panel to add your keywords?

Stephen Marsh
Community Expert
Community Expert
March 17, 2023
quote

If you are opening the files anyway, why not use the File Info panel to add your keywords?


By @Lumigraphics

 

The files are JPEG, best practice is not to decompress/recompress the image data when only metadata edits are required (not the end of the world, but still).

 

There is a limited, set/static list of 10 master keywords that need to be selected from by the user. Not all images will use the same keywords, however, they will all share certain keywords from the static master set of 10. Keyword autocomplete in File Info could possibly work here, but isn't ideal.

 

I still think that Bridge is the best place for this, even if it involves using another program, however, I understand the desire to keep this all in Photoshop.

 

Legend
March 17, 2023

Yeah I'm not clear on what he's doing for workflow. Opening a bunch of JPEGS is not best practice. And Photoshop isn't the right app for this.

Stephen Marsh
Community Expert
Community Expert
March 16, 2023

@c.pfaffenbichler & @Vibi Dev 

 

Apologies, it was a long day yesterday! After a good nights sleep, the obvious leapt out at me! I had forgotten that there was a file filter for only JPEG|JPG and I was working on a PSD test image.

 

A quick test and things are looking better, I'll come back to you later with more comments.

Vibi DevAuthor
Inspiring
March 17, 2023

Great @Stephen Marsh Thanks for the update.

c.pfaffenbichler
Community Expert
Community Expert
March 16, 2023

What about existing keywords? 

Should those be replaced or added to? 

Vibi DevAuthor
Inspiring
March 16, 2023

The existing one if any, can be replaced. Thanks 

c.pfaffenbichler
Community Expert
Community Expert
March 16, 2023

@c.pfaffenbichler 

 

It’s not updating for me...

 

If I enter:

 

1,2,3

 

The raw metadata should show the following:

 

<dc:subject>
  <rdf:Bag>
    <rdf:li>1</rdf:li> 
    <rdf:li>2</rdf:li> 
    <rdf:li>3</rdf:li> 
  </rdf:Bag>
</dc:subject>

 


Strange, if I enter »1,2,3« in the prompt I get the three numbers in the Keywords when I open the images from the selected Folder subsequently. 

Stephen Marsh
Community Expert
Community Expert
March 15, 2023

@Vibi Dev – I'd suggest that you simply use Adobe Bridge's Keywords panel, rather than reinventing the wheel.

 

When testing your script I had to change:

 

 

var files = folder.getFiles();

 

 

to:

 

 

var files = folder.getFiles(/\.(jpg|jpeg)$/i);

 

 

To overcome an error (Mac).

 

P.S. It is far more efficient to write the dc:subject metadata directly into the file object than actually opening the file.

Vibi DevAuthor
Inspiring
March 16, 2023

It's still not working with the changes made. Could you please help? 

Stephen Marsh
Community Expert
Community Expert
March 16, 2023

I'm not sure if I can, however, I'd suggest that you simply use Adobe Bridge's Keywords panel, rather than reinventing the wheel.