Oll
Oll

Reputation: 312

Converting .bmp to .png using powershell causes memory leak

Intro

I am trying to convert '.bmp' files to '.png' files. I found a piece of code earlier that does this using PowerShell. What happens is with every image converted the increment increased in my RAM usage is roughly equal to the size of an image. This increases to the max RAM I have and slows down my PC.

Question

Do I need to release the loaded images from RAM, and if so, how would I do this?

Upvotes: 1

Views: 1081

Answers (1)

Tomalak
Tomalak

Reputation: 338316

A System.Drawing.Bitmap is disposable. Dispose it after use. Also, there is no need to re-define functions or re-load assemblies multiple times.

[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()
    }  
}

Upvotes: 3

Related Questions