PowerShell:图像的高度和宽度

3

我有一个带有照片的文件夹,我想删除那些高度大于宽度的照片。我知道可以使用Powershell来实现,但不知道具体操作步骤。请帮我一下吗?

3个回答

3

其中一种技术是使用shell.application COM对象。以下是如何使用它来获取给定文件夹中所有图像的列表,以及它们的宽度/高度和是否为纵向方向(即高>宽):

$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)
            }
        }
    }

这将会产生如下输出:
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

如果你希望自动删除肖像文件,只需在最后一个括号后添加此行代码: | Where-Object IsPortrait | ForEach-Object {Remove-Item -Path $_.Image -Force}
请注意保留HTML标签。

非常感谢您的帮助。它起作用了! 最好的祝福 - undefined

1
一个更易理解的简单代码:我已经使用了-whatif进行测试,当你确认无误后,请将其关闭。
(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
    }
  }

谢谢你的帮助!这对我来说不起作用:[System.Drawing.Image] - undefined

1
你可以使用 System.Drawing 类型来完成这种工作。
$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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接