7 Replies Latest reply on May 2, 2017 1:20 AM by Laubender

    Script to get the image height and width

    IngyNorw Level 1

      I need to know the size (dimensions) of images placed in an InDesign 5.5 document.

       

      I have made the following script by combining different code. It gets the metadata OK, but the witdh and height are empty. Am I using getProperty wrong?

       

      // Refr
      // https://forums.adobe.com/thread/288764
      // https://forums.adobe.com/thread/2288546  
          
          var scriptName = "Get description from selected link",  
          doc;  
            
          PreCheck();  
            //exif:PixelXDimension   tiff:ImageWidth
          //===================================== FUNCTIONS ======================================  
          function Main(image) {  
              var link = image.itemLink,  
              metadata = link.linkXmp,   
              description = metadata.description,
              format = metadata.format,
              author = metadata.author,
              modificationDate= metadata.modificationDate,
              creator = metadata.creator,
              myLinkWidth = metadata.getProperty("http://ns.adobe.com/tiff/1.0/", "tiff:ImageWidth"),
              myLinkLength = metadata.getProperty("http://ns.adobe.com/tiff/1.0/", "tiff:ImageLength"), 
              Width = metadata.getProperty("http://ns.adobe.com/exif/1.0/", "exif:PixelXDimension"),
              Height = metadata.getProperty("http://ns.adobe.com/exif/1.0/", "exif:PixelYDimension"); 
             alert("Description is: '" + description + "'\nFormat: " + format + "\nAuthor: " + author + "\nDate modified: " + modificationDate + "\nCreator: " + creator, scriptName, false); 
              alert("Pixel dimentions of image:\nWidth: " + myLinkWidth + Width + " pixels\nHeight: " + myLinkLength + Height +" pixels");
          }  
          //--------------------------------------------------------------------------------------------------------------------------------------------------------  
          function PreCheck() {  
              var image;  
              if (app.documents.length == 0) ErrorExit("Please open a document and try again.", true);  
              doc = app.activeDocument;  
              if (doc.converted) ErrorExit("The current document has been modified by being converted from older version of InDesign. Please save the document and try again.", true);  
              if (!doc.saved) ErrorExit("The current document has not been saved since it was created. Please save the document and try again.", true);  
              if (app.selection.length == 0 || app.selection.length > 1) ErrorExit("One image should be selected.", true);  
                
              if (app.selection[0].constructor.name == "Image") { // image selected with white arrow  
                  image = app.selection[0];  
              }  
              else if (app.selection[0].images.length > 0) { // container selected with black arrow  
                  image = app.selection[0].images[0];  
              }  
              else {  
                  ErrorExit("No image in the selection.", true);  
              }  
            
              Main(image);  
          }  
          //--------------------------------------------------------------------------------------------------------------------------------------------------------  
          function ErrorExit(error, icon) {  
              alert(error, scriptName, icon);  
              exit();  
          }  
          //--------------------------------------------------------------------------------------------------------------------------------------------------------  
      

       

      I'll explain why I'm doing this:

      I'm making a magazine and the photos we get are in all different sizes and quality. In a layer called "picName" I have text frames on top of images with information from Text Variables such as name of file, PPI, actual PPI, dimensions, and scale. I make a pdf of the magazine and while my editor proof reads and edits the document I fix the photos (I cannot use InDesign at same time as she.). I use the information from the picName-layer and an Excel-sheet to determine the right size of the images, and then I edit the images in Photshop.

       

      It would be a lot easier to have the calculation in the pdf itself. What I hope to achive is:

       

      1. Get the width (W) of the linked image.
      2. Get the PPI (P) of the linked image.
      3. Get the scale (S) of the image in the frame (percent).
      4. Calculate the width the image should have: W * S * 300 / P
      5. Insert the width the image should have in a text frame in the picName-layer on top of the image.
        • 1. Re: Script to get the image height and width
          Kasyan Servetsky Level 5

          Try this:

          var myLinkWidth = metadata.getProperty("http://ns.adobe.com/tiff/1.0/", "tiff:ImageWidth");
          var myLinkLength = metadata.getProperty("http://ns.adobe.com/tiff/1.0/", "tiff:ImageLength");
          

          because the properties are here:

          30-04-2017 11-45-59.png

          — Kas

          • 2. Re: Script to get the image height and width
            IngyNorw Level 1

            Thank you. I now tried this:

             

            var image = app.selection[0].images[0];  
            var link = image.itemLink;  
            var metadata = link.linkXmp;
            var myLinkWidth = metadata.getProperty("http://ns.adobe.com/tiff/1.0/", "tiff:ImageWidth");  
            var myLinkLength = metadata.getProperty("http://ns.adobe.com/tiff/1.0/", "tiff:ImageLength");  
            alert("Pixel dimentions of image:\nWidth: " + myLinkWidth + " pixels\nHeight: " + myLinkLength +  " pixels");
            
            

             

            But the variables are still empty. It seems like the new code is doing the exact thing as in lines 19 & 20 of the original script.

             

            Could you please test it in your InDesign and see if it works? Thank you!

            • 3. Re: Script to get the image height and width
              Peter Kahrel Adobe Community Professional & MVP

              'metadata' is not a property. Use linkXmp:

               

              app.documents[0].links[0].linkXmp.getProperty("http://ns.adobe.com/tiff/1.0/", "tiff:ImageLength");

               

              But that returns 'undefined' most of the time.

               

              Why not use the image's or its parent's geometricBounds?

              • 4. Re: Script to get the image height and width
                IngyNorw Level 1

                Sorry, I don't have time to explain, but this code works!

                //Refr
                //https://indisnip.wordpress.com/2010/09/02/quicktip-insert-text-variable-to-text-frame/
                
                //DESCRIPTION:Label image with its size
                // Jongware, 13-Jan-2012
                // No Guarantees, Etc.
                
                // https://indesignsecrets.com/topic/script-to-label-selection-with-height-and-width
                
                if (app.selection[0] instanceof Rectangle) //Check if selected object is a graphic frame (I can't find a way to check if it is a linked image
                {
                  app.doScript(labelItem, ScriptLanguage.JAVASCRIPT, app.selection[0], UndoModes.ENTIRE_SCRIPT, "Label Image Size");
                } else
                {
                  alert ("No valid selection.\nPlease select an image with the black arrow before running this script.");
                }
                
                function labelItem (item)
                {
                var myDocument = app.activeDocument;
                
                //Define variables as text-variables from the document
                var tvDim = app.activeDocument.textVariables.item("dim"); 
                var tvPPI = app.activeDocument.textVariables.item("PPI"); 
                var tvPPIb = app.activeDocument.textVariables.item("PPI b"); 
                var tvProsent = app.activeDocument.textVariables.item("prosent");     
                    
                    //Get name of image, without file type
                    var mySel = app.selection[0];
                    var myImageName = mySel.graphics[0].itemLink.name; 
                    var myImageName = myImageName.slice(0,-4);
                    var myTextFrame = myDocument.textFrames.item(myImageName);    
                    
                  // Save current selected layer because adding one will make it active!
                  activeLayer = app.activeDocument.layoutWindows[0].activeLayer;
                  // Make sure the layer "bildenavn" exists
                  try {
                    app.activeDocument.layers.add({name:"bildenavn", ignoreWrap:true, layerColor: [90,192,90], printable: true});
                  } catch (_) { }
                  reportLayer = app.activeDocument.layers.item("bildenavn");
                
                  // Make sure the swatch "bildenavn" exists
                  try {
                    app.activeDocument.colors.add({name:"bildenavn", space:ColorSpace.RGB, colorValue:[90,192,90], colorModel:ColorModel.PROCESS});
                  } catch (_) { }
                  reportGreen = app.activeDocument.swatches.item("bildenavn");
                
                  // Make sure the paragraph style "bildeinfo" exists
                  try {
                    app.activeDocument.paragraphStyles.add({name:"bildeinfo", appliedFont:"Kozuka Gothic Pro", pointSize:18, fillColor:[Paper], linecoler:[black], justification: Justification.CENTER_ALIGN});
                  } catch (_) { }
                  reportStyle = app.activeDocument.paragraphStyles.item("bildeinfo");
                
                  // Make sure measurement units are in mm  
                  hmmu = app.activeDocument.viewPreferences.horizontalMeasurementUnits;
                  vmmu = app.activeDocument.viewPreferences.verticalMeasurementUnits;
                  
                  app.activeDocument.viewPreferences.horizontalMeasurementUnits = MeasurementUnits.MILLIMETERS;
                  app.activeDocument.viewPreferences.verticalMeasurementUnits = MeasurementUnits.MILLIMETERS;  
                  
                  // .. and Smart Quotes is Off
                  sqt = app.activeDocument.textPreferences.typographersQuotes;
                  app.activeDocument.textPreferences.typographersQuotes = false;
                  // Save all of the previous settings to be able to restore them later :)
                
                  // fetch width and height for the numbers, left and bottom for the lines
                  gb = item.geometricBounds;
                  // gb now holds [ top, left, bottom, right ] values -- get shorthand values
                  top = gb[0];
                  left = gb[1];
                  bottom = gb[2];
                  right = gb[3];
                
                  width = Math.round(Math.abs(right - left)*1000)/1000;
                  height= Math.round(Math.abs(bottom - top)*1000)/1000;
                
                  // Retrieve the current page.
                  // Actually, in CS5 and newer, page items have a property for this (parentPage),
                  // but I don't have that one near, and it's also nicer to make it work in CS4
                  // (and possibly even in older versions).
                  pg = item.parent;
                  while (1)
                  {
                    if (pg instanceof InsertionPoint)
                      pg = pg.parentTextframes[0];
                    if (pg instanceof Document || pg instanceof Spread || pg instanceof Page)
                      break;
                    pg = pg.parent;
                  }
                  // Draw text frame #1: Height
                  // Put it at the left of the selection, 0.5" wide and 0.2" off the left side
                  frh = pg.textFrames.add(reportLayer, {geometricBounds:[ top +10, left +10, top +55, left + 80 ], name: myImageName,
                    textFramePreferencestextFramePreferences: {verticalJustification: VerticalJustification.CENTER_ALIGN, 
                    ignoreWrap: true } });
                  // ... and put text into it.
                  
                  frh.insertionPoints[0].appliedParagraphStyle = reportStyle;
                
                //Insert these text variables into the image's text frame
                myTextFrame.texts[0].textVariableInstances.add({associatedTextVariable:tvDim});
                myTextFrame.parentStory.insertionPoints.item(-1).contents = "\rEffektiv PPI: ";
                myTextFrame.texts[0].textVariableInstances.add({associatedTextVariable:tvPPI});
                myTextFrame.parentStory.insertionPoints.item(-1).contents = "\rBildets PPI: ";
                myTextFrame.texts[0].textVariableInstances.add({associatedTextVariable:tvPPIb});
                myTextFrame.parentStory.insertionPoints.item(-1).contents = "\rSkala: ";
                myTextFrame.texts[0].textVariableInstances.add({associatedTextVariable:tvProsent});
                
                //Make the result of the text variabelts into integer
                var mySel = app.selection[0];
                //var myVarValue = mySel.textVariableInstances.item("File Name").resultText;
                var myDim = myDocument.textFrames.item(myImageName).textVariableInstances.item("dim").resultText;
                var myPPI = myDocument.textFrames.item(myImageName).textVariableInstances.item("PPI").resultText;
                var myPPIb= myDocument.textFrames.item(myImageName).textVariableInstances.item("PPI b").resultText;
                var myProsent = myDocument.textFrames.item(myImageName).textVariableInstances.item("prosent").resultText;
                
                var myWidth = myDim.slice(0,4);
                var intMyWidth = parseInt(myWidth);
                var intPPI = parseInt(myPPI);
                var intPPIb = parseInt(myPPIb);
                var myProsent = myProsent.slice(0,-1);
                var intProsent = parseInt(myProsent);
                
                var newWidth = intMyWidth *  intProsent * 300 / intPPIb / 100;
                var newWidth = Math.ceil(newWidth)
                //Remove
                var myMetadataString = "\nBredde " + intMyWidth + "\nNy bredde " + newWidth;
                frh.parentStory.insertionPoints.item(-1).contents  = String(myMetadataString);
                
                  // Restore old layer selection
                  app.activeDocument.layoutWindows[0].activeLayer = activeLayer;
                
                  // Restore previous global settings
                  app.activeDocument.viewPreferences.horizontalMeasurementUnits = hmmu;
                  app.activeDocument.viewPreferences.verticalMeasurementUnits = vmmu;
                  app.activeDocument.textPreferences.typographersQuotes = sqt;
                
                }
                
                
                
                
                • 5. Re: Script to get the image height and width
                  Ananth@desgin Level 2

                  Hi,

                   

                   app.documents.item(0).viewPreferences.horizontalMeasurementUnits = MeasurementUnits.points;  
                   app.documents.item(0).viewPreferences.verticalMeasurementUnits = MeasurementUnits.points;
                  var selected = app.selection[0].images[0];    
                  //~ var link = selected.itemLink; 
                  var h = selected.visibleBounds[2] - selected.visibleBounds[0];
                  var w = selected.visibleBounds[3] - selected.visibleBounds[1];
                  alert('height: '+h+'\nwidth: '+w);
                  

                   

                   

                  Thanks

                  • 6. Re: Script to get the image height and width
                    Kasyan Servetsky Level 5

                    Happy May 1st, dear forum! :-)

                    Could you please test it in your InDesign and see if it works? Thank you!

                    It works for me, but not with every image:

                    01-05-2017 14-59-00.png

                    For some images metadata is unavailable -- grayed out.

                    01-05-2017 14-53-04.png

                    — Kas

                    • 7. Re: Script to get the image height and width
                      Laubender Adobe Community Professional & MVP

                      Hi IngyNorw ,

                      I did a quick test with the script you posted with reply 4 written by Jongware as it seems.

                       

                      Glad, that it works for you.

                      But it did not work with a CC 2017.1 document where just one image was placed.

                      Tested with InDesign CC 2017.1 on Mac OSX 10.10.5.

                      You ran the script on InDesign CS 5.5.

                       

                      It seems that are too many changes with InDesign since the days this script was written.

                       

                      Regards,
                      Uwe