将透明的png转换为jpg powershell

4
我正在尝试批量将一些透明的png图片转换为jpg格式,下面这个拼凑出来的powershell代码可以工作,但是每次转换之后所有的图片都变成了黑色。我尝试了这里的答案Convert Transparent PNG to JPG with Non-Black Background Color,但是我得到了“using”关键字不受支持的提示(在模块中也找不到它)。
$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
你所引用的答案是用C#编写的,而不是PowerShell。 PowerShell没有using语句来保证对象的释放,这就是为什么你会得到那个语法错误的原因。请参见如何在PowerShell中实现using语句? - Lance U. Matthews
1个回答

7

基于将透明PNG转换为具有非黑色背景颜色的JPG的答案

$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
}  

你正在查看的帖子是使用C#编写的。这里介绍了在PowerShell中调用相关类和对象的相同方法。 - Shawn Esterman

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接