以下是一个使用PowerShell将BMP图像批量转换为JPG(质量85)的脚本:
<#
.SYNOPSIS批量将BMP图像转换为JPG格式(质量85)
.DESCRIPTION此脚本会遍历指定文件夹中的所有BMP文件,并将它们转换为JPG格式,质量为85
.PARAMETER SourcePath包含BMP文件的源文件夹路径
.PARAMETER DestinationPath输出JPG文件的目标文件夹路径(可选,默认为源文件夹)
.EXAMPLE.\Convert-BmpToJpg.ps1 -SourcePath "C:\Images" -DestinationPath "C:\ConvertedImages"
#>param([Parameter(Mandatory=$true)][string]$SourcePath,[string]$DestinationPath = $SourcePath
)# 加载必要的程序集
Add-Type -AssemblyName System.Drawing# 创建目标目录(如果不存在)
if (!(Test-Path -Path $DestinationPath)) {New-Item -ItemType Directory -Path $DestinationPath | Out-Null
}# 获取所有BMP文件
$bmpFiles = Get-ChildItem -Path $SourcePath -Filter "*.bmp"# 设置JPEG编码器参数(质量85)
$encoder = [System.Drawing.Imaging.ImageCodecInfo]::GetImageEncoders() | Where-Object { $_.FormatDescription -eq "JPEG" }
$encoderParams = New-Object System.Drawing.Imaging.EncoderParameters(1)
$encoderParams.Param[0] = New-Object System.Drawing.Imaging.EncoderParameter([System.Drawing.Imaging.Encoder]::Quality, 85)# 转换每个文件
foreach ($file in $bmpFiles) {try {$inputPath = $file.FullName$outputPath = Join-Path -Path $DestinationPath -ChildPath ($file.BaseName + ".jpg")Write-Host "正在转换: $($file.Name) -> $($file.BaseName).jpg"# 读取BMP文件$image = [System.Drawing.Image]::FromFile($inputPath)# 保存为JPG$image.Save($outputPath, $encoder, $encoderParams)# 释放资源$image.Dispose()Write-Host "转换完成: $($file.BaseName).jpg" -ForegroundColor Green}catch {Write-Host "转换 $($file.Name) 时出错: $_" -ForegroundColor Red}
}Write-Host "所有转换操作已完成!" -ForegroundColor Cyan
使用说明:
-
将上述代码保存为
.ps1
文件,例如Convert-BmpToJpg.ps1
-
在PowerShell中运行脚本:
.\Convert-BmpToJpg.ps1 -SourcePath "C:\YourBmpFolder" -DestinationPath "C:\OutputFolder"
(如果省略
-DestinationPath
参数,输出文件将保存在源文件夹中) -
脚本会处理指定文件夹中的所有
.bmp
文件,并将它们转换为质量为85的.jpg
文件
注意事项:
- 需要.NET Framework支持(通常Windows系统都已安装)
- 原始BMP文件不会被删除
- 如果目标文件夹中有同名JPG文件,它们会被覆盖
- 转换大文件可能需要一些时间
如果需要调整JPG质量,可以修改$encoderParams.Param[0]
中的85为其他值(1-100)。