powershell - 将透明png转换为jpg powershell

标签 powershell

我正在尝试将一堆透明的 png 文件批量转换为 jpg 文件,下面的鹅卵石 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)
}  

据我了解,您需要创建一个新的白色背景位图图形并在其上绘制此图像,但我一直不知道如何添加它。

最佳答案

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

关于powershell - 将透明png转换为jpg powershell,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47602716/

相关文章:

function - Powershell 函数中的可重复参数(最好是链接参数集)

powershell - 检查文件夹是否存在错误

c# - 无法在 C# 中导入 AzureAD 模块

xml - 如何在 powershell 中获取子 XML 节点的所有父节点

powershell - 问题使脚本在Powershell中接受带空格和破折号的组名

powershell - 如何删除所有 XML 子节点但不删除 Powershell 中的属性

powershell - VBS脚本等待返回

通过 jmeter/BSF 采样器/beanshell 运行时 powershell/powershell 挂起

powershell - 使用 powershell 创建 TFS API 发布

PowerShell:模块、它们的位置和重新加载