Powershell: height and width of an image

Viewed 1186

I have a folder with photos and I want to delete those whose height is greater than width. I know that with Powershell you can but I don't know how to do it. They help me?

3 Answers

One technique is to use the shell.application COM object. Here's how to use it to get a list of all the images in a given folder, together with their width/height and if they are in portrait orientation (i.e. height > width):

$targetFolder = "C:\ImageFolder"
$shellApp = New-Object -ComObject 'shell.application'
$folderNamespace = $shellApp.Namespace($targetFolder)

Get-ChildItem -Path "$targetFolder\*" -Include '*.jpg','*.png' -File |
    ForEach-Object {
        $image = $folderNamespace.ParseName($_.Name)

        if($folderNamespace.GetDetailsOf($image, 31) -match '(?<width>\d+) x (?<height>\d+)') {
            [PsCustomObject]@{
                    Image      = $_.FullName
                    Width      = $Matches.width
                    Height     = $Matches.height
                    IsPortrait = $([int]$Matches.height -gt [int]$Matches.width)
            }
        }
    }

This gives output like this:

Image                      Width Height IsPortrait
-----                      ----- ------ ----------
C:\ImageFolder\Image1.jpg  527   750          True
C:\ImageFolder\Image2.jpg  750   500         False
C:\ImageFolder\Image3.jpg  466   750          True
C:\ImageFolder\Image4.jpg  506   700          True
C:\ImageFolder\Image5.jpg  654   700          True
C:\ImageFolder\Image6.jpg  700   521         False
C:\ImageFolder\Image7.jpg  598   700          True
C:\ImageFolder\Image8.jpg  570   700          True
C:\ImageFolder\Image9.jpg  700   700         False
C:\ImageFolder\Image10.jpg 700   899          True

If you want it to automatically delete the portrait files, you can just append this line after the last bracket:

| Where-Object IsPortrait | ForEach-Object {Remove-Item -Path $_.Image -Force}

a simple code easier to understand: i have let the -whatif to test, when you are ok,put off

(Get-ChildItem "C:\path\*" -Include *.png, *.jpg).FullName | 
  ForEach-Object { 
    $img = [System.Drawing.Image]::FromFile($_); 
    $dimensions = "$($img.Width) x $($img.Height)"

    If ($img.Width -gt $img.Height) {
        Remove-Item $_ -whatif
    }
  }

You can do this sort of work using the System.Drawing type.

$imageFile = get-item '.\Berserk 26 spread.png'
$imageObject = [System.Drawing.Image]::FromFile($imageFile.FullName); 
$imageObject.GetType()

"The file $($imageFile.Name) has a width of $($imageObject.Width) and a height of $($imageObject.Height)"

"Is the file wider than it is tall?"
($imageObject.Width -ge $imageObject.Height)

#Output
The file Berserk 26 spread.png has a width of 3000 and a height of 1982
Is the file wider than it is tall?
True
Related