首页 > 解决方案 > 我有一个文件夹,其中包含多个包含图像的文件夹。我想根据尺寸过滤图像

问题描述

此代码正确显示 ImageName 和 FolderName,但 Dimension 保持空白。正确显示的数据未保存在 csv 文件中。

此外,如果基于维度的条件不起作用。

#-----------powershell script------------
foreach ($folder in $Folders) { 
    $Images = Get-ChildItem  -Path $Folder -Filter *.png
    $Results = @()
    foreach ($image  in $Images) { 
        $dimensions = $image.Dimensions
        # $dimensions = "$($image.Width) x $($image.Height)"
        If ($dimensions -ne '1000 x 1000') {


            $Results += [pscustomobject]@{
                ImageName  = $image
                FolderName = $Folder
                Dimension  = $dimensions
            }
        }
    }



    $Results | FT -auto

    # $ExcelData= Format-Table -property @{n="$image";e='$Folder'}
    $Results | Export-csv "C:\Users\M1036098\Documents\Imagelessthan1000pi.txt" -NoTypeInformation

}

输出中的维度属性保持空白

标签: powershell

解决方案


所以让我们回顾一下为什么这不起作用。Get-ChildItem带回对象System.Io.FileInfo

System.IO.FileIonfo我们可以从 Microsoft 看到没有名为Dimensions 的方法或属性。

那么让我们得到这些尺寸......

首先,我们要将图像加载到内存中并获取大小。

$Folders = @("C:\Test")

$Folders | %{
    $Folder = $_
    Get-ChildItem  -Path $_ -Filter *.png | %{
        try{
            $Image = New-Object System.Drawing.Bitmap "$($_.FullName)"
            [pscustomobject]@{
                ImageName  = $_.Name
                FolderName = $Folder
                Dimension  = "$($Image.Height) x $($Image.Width)"
            }
        }catch{
        }
    } | ?{
        $_.Dimension -ne "1000 x 1000"
    }
}

输出看起来像

ImageName     FolderName     Dimension  
---------     ----------     ---------  
Test1.png     C:\Test        1440 x 2560
Test2.png     C:\Test        1200 x 1200

编辑:为 Sonam 添加功能。根据发布的答案。

function Get-ImageDimension([string]$Path, [array]$ImageExtensions, [array]$ExcludeDimensions){

    Get-ChildItem -Path $Path -Include $ImageExtensions -Recurse | foreach-object{
        try{
            $image = [Drawing.Image]::FromFile($_);
            [pscustomobject]@{
                ImageName = $_.Name
                FolderName = $_.DirectoryName
                Dimension= "$($image.Width) x $($image.Height)"
            }
        }catch{
        }
    } | ?{
        $ExcludeDimensions -notcontains $_.Dimension
    }
}


Get-ImageDimension C:\Test\ -ImageExtensions *.png -ExcludeDimensions "1000 x 1000" | export-csv C:\Test\Test.csv

推荐阅读