Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting transparent png to jpg powershell

Tags:

powershell

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.

like image 567
evobe Avatar asked Oct 19 '25 12:10

evobe


1 Answers

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
}  
like image 131
Shawn Esterman Avatar answered Oct 22 '25 10:10

Shawn Esterman



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!