2

I'm writing a script to bulk remove transparency from .gif files. The result must still be in .gif format.

Tried conversion to .jpeg and back, but the transparent layer was not removed. Script shown below. Also tried color depth, but did not work. How to do so?

Reformatted the script to take up less space in the post.

function ConvertImage{
    Param (
        [string]$path,
        [string]$inputFormat,
        [string]$outputFormat,
        [bool]$newName
    )

    if (Test-Path $path) {
        [Reflection.Assembly]::LoadWithPartialName("System.Windows.Forms") | Out-Null
        $codec = [Drawing.Imaging.ImageCodecInfo]::GetImageEncoders() |
                 Where-Object { $_.FormatDescription -eq "$outputFormat" }  
        $ep = New-Object Drawing.Imaging.EncoderParameters 
        $ep.Param[0] = New-Object Drawing.Imaging.EncoderParameter ([System.Drawing.Imaging.Encoder]::Quality, [long]100)
        foreach ($file in (ls "$path\*.$inputFormat")) {
            $convertfile = New-Object System.Drawing.Bitmap($file.Fullname)
            if ($newName) {
                [string]$newName = $file.DirectoryName + "\New-" + $file.Name
                $newfilname = ($newName -replace "([^.]).$inputFormat",'$1') + ".$outputFormat"
            } else {
                $newfilname = ($file.FullName -replace "([^.]).$inputFormat",'$1') + ".$outputFormat" 
            }  
            $convertfile.Save($newfilname, $codec, $ep)
            $newfilname #showing which file is processed
            Start-Sleep -Milliseconds 200 #slowing down a bit
        } 
    } else {
        Write-Host "path not found."
    }
}
ConvertImage -path "C:\Images" -inputFormat "gif" -outputFormat "jpeg" -newName $true
Read-Host "First conversion complete. Continue"
ConvertImage -path "C:\Images" -inputFormat "jpeg" -outputFormat "gif" -newName $false
Ansgar Wiechers
  • 193,178
  • 25
  • 254
  • 328
Jlisk
  • 153
  • 1
  • 1
  • 8
  • Why do you load System.Windows.Forms? – marsze Jan 24 '19 at 12:56
  • Have you considered using ImageMagick instead? – Ansgar Wiechers Jan 24 '19 at 14:41
  • @marsze I have used a code found on internet as a basis, which I edited. System.Windows.Forms is probably a relict of that, my bad. – Jlisk Jan 25 '19 at 05:09
  • @AnsgarWiechers I'm in a corporate environment, I can not use external tools. – Jlisk Jan 25 '19 at 05:09
  • Just a tip, anytime you can't find out how to do something in powershell, try searching for the C# version. Translating C# to Powershell is usually pretty easy. This solution looks like it would work for you. https://stackoverflow.com/a/35179005/5339918 – RiverHeart Mar 30 '19 at 03:28

0 Answers0