Home > OS >  Converting .bmp to .png using powershell causes memory leak
Converting .bmp to .png using powershell causes memory leak

Time:04-12

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?

Code

The code I am using is from here: Memory usage

Code used:

$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','$1')   ".png"
            $convertfile.Save($newfilname, "png")
            $file.Fullname
    }  
 }
};ConvertImage -path $args[0] 
}

PS. I would prefer to keep using PowerShell, as I use this for further processing the data.

CodePudding user response:

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()
    }  
}
  • Related