Reputation: 71
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.
Upvotes: 4
Views: 5420
Reputation: 2342
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
}
Upvotes: 8