powershell 实现批量把文件夹下的bmp文件转换为jpg
以下是一个使用PowerShell将BMP图像批量转换为JPG(质量85)的脚本:
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)。