使用 powershell 将 .bmp 转换为 .png 会导致内存泄漏

Converting .bmp to .png using powershell causes memory leak

简介

我正在尝试将“.bmp”文件转换为“.png”文件。我之前发现了一段使用 PowerShell 执行此操作的代码。发生的情况是,每转换一张图像,我的 RAM 使用量增加的增量大致等于图像的大小。这增加了我拥有的最大 RAM 并减慢了我的电脑速度。

问题

我是否需要从 RAM 中释放加载的图像,如果需要,我该怎么做?

代码

我使用的代码来自这里:https://code.adonline.id.au/change-image-formats-powershell/

使用的代码:

$usb1 = 'U:'
$usb2 = 'F:'
$usb3 = 'H:'
$usb4 = 'J:'
$usb5 = 'K:'
$usb6 = 'I:'

$usblist = $usb1,$usb2,$usb3,$usb4,$usb5,$usb6

foreach($usbs in  $usblist){
$usb = $usbs
############################# convert ###################################
function ConvertImage{
    param ([string]$path)
        foreach($path in Get-ChildItem -Directory $usb -Recurse){
Write-Host $path
            #Load required assemblies and get object reference  
    [Reflection.Assembly]::LoadWithPartialName("System.Windows.Forms") | Out-Null
        foreach($file in (ls "$path\*.bmp")){
            $convertfile = new-object System.Drawing.Bitmap($file.Fullname)
            $newfilname = ($file.Fullname -replace '([^.]).bmp','') + ".png"
            $convertfile.Save($newfilname, "png")
            $file.Fullname
    }  
 }
};ConvertImage -path $args[0] 
}

PS。我更愿意继续使用 PowerShell,因为我用它来进一步处理数据。

一个System.Drawing.Bitmap is disposable. Dispose就用完了。此外,无需多次 re-define 函数或 re-load 程序集。

[Reflection.Assembly]::LoadWithPartialName("System.Windows.Forms") | Out-Null

$paths = 'U:', 'F:', 'H:', 'J:', 'K:', 'I:'

foreach ($path in $paths) {
    Get-ChildItem -File "$path\*.bmp" -Recurse | ForEach-Object {
        $bitmap = [System.Drawing.Bitmap]::new($_.FullName)
        $newname = $_.FullName -replace '.bmp$','.png'
        $bitmap.Save($newname, "png")
        $bitmap.Dispose()
    }  
}