将透明png转换为jpg powershell

时间:2017-12-01 23:03:16

标签: powershell

我试图将一堆透明的png批量转换为jpgs,而下面的鹅卵石PowerShell可以正常工作,但每当我转换所有图像时都会变黑。我在这里尝试了答案 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)
}  

根据我的理解,你需要创建一个带有白色背景的新位图图形,然后在上面绘制图像,但对于我的生活,我无法弄清楚如何添加它。

1 个答案:

答案 0 :(得分:0)

基于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)
}