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.
The Modern Method (Recommended): Using PowerShell
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:
Add-Type -AssemblyName System.Drawing;: This command loads the necessary .NET assembly that contains the tools for working with images.$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.Write-Output ('{0}x{1}' -f $img.Width,$img.Height): This part formats the output.$img.Widthand$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 finalWidthxHeightoutput (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:
- The batch script sets the
ImageFilevariable. - The
FOR /Floop executes the long PowerShell command. The%ImageFile%batch variable is expanded into the command string before PowerShell runs. - PowerShell loads the image, gets its width and height, formats them as
1920x1080, and prints this string to its output. - The
FOR /Floop captures this single line of output and theSET "Dimensions=%%D"command assigns it to our batch variable. - 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.Drawingcan read, the PowerShell command will throw an error and produce no output.- Solution: The script above handles this gracefully. The
FOR /Floop will not run, theDimensionsvariable will remain undefined, and theIF DEFINEDcheck will report the failure. You should always useIF EXISTto check for the file first.
- Solution: The script above handles this gracefully. The
-
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 callingpowershell.exeonce 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 /Floop 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.