4

I'm trying to batch convert a bunch of transparent pngs to jpgs and the below cobbled powershell works but whenever I convert all images come out black. I tried the answer here Convert Transparent PNG to JPG with Non-Black Background Color but I get "using" keyword is not supported (couldn't find it in the modules either)

$files = Get-ChildItem "C:\Pictures\test" -Filter *.png -file -Recurse | 
foreach-object {

    $Source = $_.FullName
    $test = [System.IO.Path]::GetDirectoryName($source)
    $base= $_.BaseName+".jpg"
    $basedir = $test+"\"+$base
    Write-Host $basedir
    Add-Type -AssemblyName system.drawing
    $imageFormat = "System.Drawing.Imaging.ImageFormat" -as [type]
    $image = [drawing.image]::FromFile($Source)
    $image.Save($basedir, $imageFormat::jpeg)
}  

From what I understand you need to create a new bitmap graphic with a white background and draw this image over that but for the life of me I can't figure out how to add it in.

evobe
  • 61
  • 1
  • 7
  • 1
    The answer you referenced is written in C#, not PowerShell. PowerShell does not have a [`using` statement](https://learn.microsoft.com/dotnet/csharp/language-reference/keywords/using-statement) to guarantee object disposal, which is why you would have gotten that syntax error. See [How to implement using statement in powershell?](https://stackoverflow.com/q/42107851/150605). – Lance U. Matthews Dec 02 '17 at 00:45

1 Answers1

7

Based on the answer from Convert Transparent PNG to JPG with Non-Black Background Color

$files = Get-ChildItem "C:\Pictures\test" -Filter *.png -file -Recurse | 
foreach-object {

    $Source = $_.FullName
    $test = [System.IO.Path]::GetDirectoryName($source)
    $base= $_.BaseName+".jpg"
    $basedir = $test+"\"+$base
    Write-Host $basedir
    Add-Type -AssemblyName system.drawing
    $imageFormat = "System.Drawing.Imaging.ImageFormat" -as [type]
    $image = [drawing.image]::FromFile($Source)
    # $image.Save($basedir, $imageFormat::jpeg) Don't save here!

    # Create a new image
    $NewImage = [System.Drawing.Bitmap]::new($Image.Width,$Image.Height)
    $NewImage.SetResolution($Image.HorizontalResolution,$Image.VerticalResolution)

    # Add graphics based on the new image
    $Graphics = [System.Drawing.Graphics]::FromImage($NewImage)
    $Graphics.Clear([System.Drawing.Color]::White) # Set the color to white
    $Graphics.DrawImageUnscaled($image,0,0) # Add the contents of $image

    # Now save the $NewImage instead of $image
    $NewImage.Save($basedir,$imageFormat::Jpeg)

    # Uncomment these two lines if you want to delete the png files:
    # $image.Dispose()
    # Remove-Item $Source
}  
joe
  • 3,752
  • 1
  • 32
  • 41
Shawn Esterman
  • 2,292
  • 1
  • 10
  • 15
  • The post you were looking at is `using` c#. This is the same thing, but calling the relevant classes and objects in PowerShell. – Shawn Esterman Dec 02 '17 at 22:58