"内存不足"使用Powershell从图片文件中提取元数据时出错

时间:2016-07-20 02:34:56

标签: powershell

使用Powershell,我想要完成的是:

  1. 遍历图像文件目录(没有文件扩展名,顺便说一句)
  2. 提取每个
  3. 的高度和宽度
  4. 仅将具有特定属性的图像文件复制到另一个目录
  5. 我目前正在做什么(不相关的代码除外):

    Get-ChildItem | ForEach-Object {
        $img = [System.Drawing.Image]::FromFile($_.FullName)
        $dimensions = "$($img.Width) x $($img.Height)"
        $size = $img.Length
        If ($dimensions -eq "1920 x 1080" -and $size -gt 100kb)
            {
            Copy-Item -Path $sourceDir\$img -Destination $destDir\$img.jpg > $null
            }
    }
    

    我收到的错误:

    Exception calling "FromFile" with "1" argument(s): "Out of memory."
    At C:\blahblah
    +     $img = [System.Drawing.Image]::FromFile($_.FullName)
    +     ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
        + CategoryInfo          : NotSpecified: (:) [], MethodInvocationException
        + FullyQualifiedErrorId : OutOfMemoryException
    

    根据我一直在研究的内容,错误来自于在内存中加载大图像文件。我已经知道流媒体是更好的方式,但我还没有找到一种方法来完成这项工作并且没有多少经验。

    我尝试用第二行代替: $img = [System.Drawing.Image]::FromStream([System.IO.MemoryStream]$_.FullName) 但它咆哮着说我无法改变" C:\ blahblah" type" System.String"的值输入" System.IO.MemoryStream"

2 个答案:

答案 0 :(得分:1)

将我的评论转换为答案:

来自docs

  

如果文件没有有效的图像格式,或者GDI +不支持文件的像素格式,则此方法会抛出OutOfMemoryException异常。

答案 1 :(得分:0)

  

我已经知道流式传输是更好的方式,但我还没有找到一种方法来完成这项工作并且没有多少经验。

try {
  # create filestream from file
  $Stream = New-Object System.IO.FileStream -ArgumentList $_.FullName,'Open'
  $Image  = [System.Drawing.Image]::FromStream($Stream)
  $dimensions = "$($Image.Width) x $($Image.Height)"
  if($dimensions -eq '1920 x 1080' -and $_.Length -gt 100kb)
  {
    # Copy-Item
  }
}
finally {
  $Image,$Stream |ForEach-Object {
    # Clean up
    $_.Dispose()
  }
}