Skip to main content

How to Get the Dimensions of an Image File in a Batch Script

Knowing the dimensions (width and height) of an image file is a common requirement for scripts that process, sort, or validate images. You might need to check if an image meets a minimum size requirement for an upload, sort images into "portrait" and "landscape" folders, or simply log the dimensions as part of an inventory.

The batch scripting environment (cmd.exe) has no built-in command to read image metadata. This is a complex task that requires a tool that can parse the binary structure of image file formats (like JPG, PNG, or GIF). The only reliable and effective solution is to delegate this task to a more powerful scripting language that is built into Windows: PowerShell.

The Challenge: Batch Can't Read Image Metadata

A batch script can see a file's name, size, and timestamp, but it cannot understand its internal content. The width and height of an image are stored as metadata inside the binary file itself. To read this, we need a tool that can parse that specific file format. Pure batch commands like TYPE or FOR /F will only see a meaningless stream of binary data.

PowerShell, which is included in all modern versions of Windows, has built-in access to .NET libraries that can easily and safely read image properties. This is the definitive and recommended method.

powershell -Command "Add-Type -AssemblyName System.Drawing; $img = [System.Drawing.Image]::FromFile('C:\Path\to\image.jpg'); Write-Output ('{0}x{1}' -f $img.Width,$img.Height)"

This one-liner is a complete solution that returns a clean WidthxHeight string.

The Core PowerShell Logic Explained

Let's break down the PowerShell command that our batch script will call:

  1. Add-Type -AssemblyName System.Drawing;: This command loads the necessary .NET assembly that contains the tools for working with images.
  2. $img = [System.Drawing.Image]::FromFile('...');: This is the core operation. It loads the image file from the specified path into a temporary image object called $img.
  3. Write-Output ('{0}x{1}' -f $img.Width,$img.Height): This part formats the output.
    • $img.Width and $img.Height: These are the properties of the image object that hold the dimensions in pixels.
    • '{0}x{1}' -f ...: This is a format string that creates the final WidthxHeight output (e.g., 1920x1080).

Exmaple Script: Capturing Dimensions with PowerShell

To use the dimensions in your batch script, you must wrap the PowerShell command in a FOR /F loop to capture its output into a variable.

@ECHO OFF
SET "ImageFile=C:\MyPhotos\vacation.jpg"
SET "Dimensions="

ECHO --- Getting image dimensions ---
ECHO File: "%ImageFile%"
ECHO.

FOR /F "delims=" %%D IN (
'powershell -NoProfile -ExecutionPolicy Bypass -Command "Add-Type -AssemblyName System.Drawing; $img = [System.Drawing.Image]::FromFile('%ImageFile%'); Write-Output ('{0}x{1}' -f $img.Width,$img.Height)"'
) DO (
SET "Dimensions=%%D"
)

IF DEFINED Dimensions (
ECHO The dimensions are: %Dimensions%
) ELSE (
ECHO Could not determine the dimensions. The file may not be a valid image.
)

How the script works:

  1. The batch script sets the ImageFile variable.
  2. The FOR /F loop executes the long PowerShell command. The %ImageFile% batch variable is expanded into the command string before PowerShell runs.
  3. PowerShell loads the image, gets its width and height, formats them as 1920x1080, and prints this string to its output.
  4. The FOR /F loop captures this single line of output and the SET "Dimensions=%%D" command assigns it to our batch variable.
  5. The script can now use the %Dimensions% variable.

Common Pitfalls and How to Solve Them

  • File Not Found or Not an Image: If the path is wrong or the file is not a valid image format that System.Drawing can read, the PowerShell command will throw an error and produce no output.

    • Solution: The script above handles this gracefully. The FOR /F loop will not run, the Dimensions variable will remain undefined, and the IF DEFINED check will report the failure. You should always use IF EXIST to check for the file first.
  • Administrator Rights: This operation does not typically require administrator rights, as it is a read-only operation on a user-accessible file.

  • Performance: Calling the PowerShell engine has a small startup overhead. If you need to process thousands of images in a loop, it is far more efficient to write the entire loop inside a single PowerShell script (.ps1) rather than calling powershell.exe once for every single file.

Practical Example: A "Sort Images by Orientation" Script

This script is a powerful and practical use case. It checks the dimensions of all .jpg files in a folder and moves them into "Landscape" or "Portrait" subfolders based on their orientation.

@ECHO OFF
SETLOCAL ENABLEDELAYEDEXPANSION

MKDIR "Landscape" 2>NUL
MKDIR "Portrait" 2>NUL
MKDIR "Square" 2>NUL

ECHO --- Sorting Images by Orientation ---
ECHO.

FOR %%F IN (*.jpg) DO (
SET "Dimensions="
SET "Width="
SET "Height="

ECHO Processing "%%F"...

REM Get the dimensions like "1920x1080"
FOR /F "delims=" %%D IN (
'powershell -Command "Add-Type -AssemblyName System.Drawing; try { $img = [System.Drawing.Image]::FromFile('%%~fF'); Write-Output ('{0}x{1}' -f $img.Width,$img.Height) } catch {}"'
) DO (
SET "Dimensions=%%D"
)

IF DEFINED Dimensions (
REM Parse the "WxH" string to get separate width and height
FOR /F "tokens=1,2 delims=x" %%W IN ("!Dimensions!") DO (
SET "Width=%%W"
SET "Height=%%X"
)

REM Compare the dimensions and move the file
IF !Width! GTR !Height! (
ECHO -> Landscape. Moving...
MOVE "%%F" "Landscape\"
) ELSE IF !Height! GTR !Width! (
ECHO -> Portrait. Moving...
MOVE "%%F" "Portrait\"
) ELSE (
ECHO -> Square. Moving...
MOVE "%%F" "Square\"
)
)
)
ENDLOCAL

Conclusion

While batch scripting cannot natively read image metadata, its ability to call PowerShell makes this a simple and highly reliable task.

  • The PowerShell [System.Drawing.Image]::FromFile() method is the standard and only recommended solution for this task.
  • The core logic can be executed with a single, self-contained one-liner.
  • Use a FOR /F loop in your batch script to capture the dimension string returned by PowerShell.

By delegating this complex task to PowerShell, you can write powerful batch scripts that can intelligently process and manage image files based on their properties.