批量转换图片大小的Powershell脚本
- 允许指定最大大小,即最大宽度或高度不超过指定的值,且保持原图比例
Powershell脚本 resize.ps1 :
param(
[string]$p="*.jpg",
[string]$s="800x600",
[string]$o="out\"
)
if ($MyInvocation.BoundParameters.Count -eq 0) {
echo "Batch resize image v1.0"
echo "Usage: resize [filter [WxH [dir]]]"
echo " Example: resize *.jpg 800x400 C:\resized"
echo " Default: filter = *.jpg, WxH=800x600, dir=.\out"
echo ""
}
if ($s -match "^(\d+)x(\d+)$") {
$w=[int]$matches[1]
$h=[int]$matches[2]
} else {
echo "Invalid size format."
exit 1
}
if (-not (Test-Path $o)) {New-Item -ItemType Directory -Path $o | Out-Null}
Add-Type -AssemblyName System.Drawing
foreach ($f in Get-ChildItem -Path . -Filter $p) {
$i=[System.Drawing.Image]::FromFile($f.FullName)
if ($i.Width -le $w -and $i.Height -le $h) {
Copy-Item $f.FullName -Destination (Join-Path -Path $o -ChildPath $f.Name)
Write-Host "Copied: $($f.Name)"
} else {
$rw=$w/$i.Width
$rh=$h/$i.Height
$sc=[Math]::Min($rw,$rh)
$nw=[int]($i.Width*$sc)
$nh=[int]($i.Height*$sc)
$ni=New-Object System.Drawing.Bitmap($nw,$nh)
$g=[System.Drawing.Graphics]::FromImage($ni)
$g.CompositingQuality=[System.Drawing.Drawing2D.CompositingQuality]::HighQuality
$g.InterpolationMode=[System.Drawing.Drawing2D.InterpolationMode]::HighQualityBicubic
$g.SmoothingMode=[System.Drawing.Drawing2D.SmoothingMode]::HighQuality
$g.DrawImage($i,0,0,$nw,$nh)
$ni.Save((Join-Path -Path $o -ChildPath $f.Name),[System.Drawing.Imaging.ImageFormat]::Jpeg)
$g.Dispose()
$i.Dispose()
$ni.Dispose()
echo "Processed: $($f.Name)"
}
}
echo "Done."