3

How can I get an image resolution in DPI with VBScript?

for example

Res= GET "M.jpg" Resolution
If Res > 100
   Echo "GOODQ"
Inside Man
  • 4,194
  • 12
  • 59
  • 119

2 Answers2

4

You gan get the image DPI using the HorizontalResolution and VerticalResolution properties of the WIA.ImageFile scripting object:

Set objImage = CreateObject("WIA.ImageFile")

objImage.LoadFile "C:\M.jpg"

If objImage.HorizontalResolution > 100 Then
  Log.Message "GOODQ (" & objImage.HorizontalResolution & " DPI)"
End If


Just for completeness, there's another solution for Windows Vista and later — using the Folder.GetDetailsOf method to read the image DPI from the extended file properties. But the code will be longer and a bit messier, because:

  • The index of the Horizontal resolution and Vertical resolution file properties are different on different Windows versions (see this page and this my answer for details).
  • The extended file properties return DPI as a string like 240 dpi; you may need to convert it to a number.

    ' For Windows 7
    Const HORIZONTAL_RESOLUTION = 161
    Const VERTICAL_RESOLUTION = 163
    
    Dim objShell : Set objShell = CreateObject("Shell.Application")
    Dim objFolder : Set objFolder = objShell.Namespace("C:\MyFolder")
    Dim objFile : Set objFile = objFolder.ParseName("M.jpg")
    
    Dim strDpi : strDpi = objFolder.GetDetailsOf(objFile, HORIZONTAL_RESOLUTION) ' Returns DPI as a string like "240 dpi"
    Dim dpi : dpi = ToInt(strDpi)
    
    If dpi > 100 Then
      Log.Message "GOODQ (" & dpi & " DPI)"
    End If
    
    ' Extracts a number from a string, e.g. "240 dpi" -> 240
    ' NB: no error handling
    Function ToInt(ValueStr)
      Dim objRE : Set objRE = New RegExp
      objRE.Pattern = "\d+"
      Dim colMatches : Set colMatches = objRE.Execute(ValueStr)
      ToInt = CLng(colMatches(0).Value)
    End Function
    
Community
  • 1
  • 1
Helen
  • 87,344
  • 17
  • 243
  • 314
1

You could do something like this using WIA Automation Library.

Set objImage = CreateObject("WIA.ImageFile")
objImage.LoadFile "M.jpg"

If objImage.Width > 100 And objImage.Height > 100 Then
    WScript.Echo "GOODQ" & vbNewLine & "Width: " & _ 
        objImage.Width & vbNewLine & _
        "Height: " & objImage.Height
End If
JustSomeQuickGuy
  • 933
  • 1
  • 10
  • 21