以下是一個使用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)。