Уменьшить фото через System.Drawing
Масштабирует изображения до заданных границ на Windows без установки сторонних библиотек.
Что делает скрипт
Скрипт использует встроенный System.Drawing, применяет ориентацию из EXIF и уменьшает кадр с сохранением пропорций. Мелкие изображения не увеличиваются, структура подпапок сохраняется. Файлы пишутся в отдельный каталог, существующие имена пропускаются без ключа Force.
Быстрый старт
powershell -File Resize-Images.ps1 -Path C:\Photos -OutDir C:\Photos\resized -MaxWidth 1920 -MaxHeight 1080
Скачайте файл, откройте терминал в папке со скриптом и выполните команду. Запускайте в PowerShell 5.1 или PowerShell 7.
Другие варианты
powershell -File Resize-Images.ps1 -Path $HOME\Pictures -OutDir $HOME\Pictures\resizedpowershell -File Resize-Images.ps1 -Path D:\Photos -OutDir D:\Photos\small -MaxWidth 1280 -MaxHeight 1280 -Recurse
Что понадобится
Встроен в Windows 10/11 (PowerShell 5.1)
Resize-Images.ps1
[CmdletBinding()]
param(
[Parameter(Mandatory = $true)]
[string]$Path,
[Parameter(Mandatory = $true)]
[string]$OutDir,
[ValidateRange(16, 20000)]
[int]$MaxWidth = 1920,
[ValidateRange(16, 20000)]
[int]$MaxHeight = 1080,
[ValidateRange(1, 100)]
[int]$JpegQuality = 90,
[switch]$Recurse,
[switch]$Force
)
$ErrorActionPreference = 'Stop'
Add-Type -AssemblyName System.Drawing
function Get-Orientation {
param([System.Drawing.Image]$Image)
try {
return [int]$Image.GetPropertyItem(274).Value[0]
}
catch {
return 1
}
}
function Apply-Orientation {
param(
[System.Drawing.Image]$Image,
[int]$Orientation
)
switch ($Orientation) {
2 { $Image.RotateFlip([System.Drawing.RotateFlipType]::RotateNoneFlipX) }
3 { $Image.RotateFlip([System.Drawing.RotateFlipType]::Rotate180FlipNone) }
4 { $Image.RotateFlip([System.Drawing.RotateFlipType]::RotateNoneFlipY) }
5 { $Image.RotateFlip([System.Drawing.RotateFlipType]::Rotate90FlipX) }
6 { $Image.RotateFlip([System.Drawing.RotateFlipType]::Rotate90FlipNone) }
7 { $Image.RotateFlip([System.Drawing.RotateFlipType]::Rotate270FlipX) }
8 { $Image.RotateFlip([System.Drawing.RotateFlipType]::Rotate270FlipNone) }
}
}
function Save-Jpeg {
param(
[System.Drawing.Bitmap]$Bitmap,
[string]$Target,
[int]$Quality
)
$encoder = [System.Drawing.Imaging.ImageCodecInfo]::GetImageEncoders() |
Where-Object { $_.MimeType -eq 'image/jpeg' } |
Select-Object -First 1
$parameters = New-Object System.Drawing.Imaging.EncoderParameters(1)
$parameter = New-Object System.Drawing.Imaging.EncoderParameter(
[System.Drawing.Imaging.Encoder]::Quality,
[long]$Quality
)
$parameters.Param[0] = $parameter
$Bitmap.Save($Target, $encoder, $parameters)
$parameters.Dispose()
}
$resolved = (Resolve-Path -LiteralPath $Path -ErrorAction Stop).Path
if (Test-Path -LiteralPath $resolved -PathType Leaf) {
$root = Split-Path -Parent $resolved
$files = @(Get-Item -LiteralPath $resolved)
}
elseif (Test-Path -LiteralPath $resolved -PathType Container) {
$root = $resolved
$files = @(Get-ChildItem -LiteralPath $resolved -File -Recurse:$Recurse -ErrorAction SilentlyContinue)
}
else {
throw "Путь не найден: $resolved"
}
$allowed = @('.jpg', '.jpeg', '.png', '.bmp', '.tif', '.tiff')
$outRoot = [System.IO.Path]::GetFullPath($OutDir)
if (-not (Test-Path -LiteralPath $outRoot)) {
New-Item -ItemType Directory -Path $outRoot -Force | Out-Null
}
$done = 0
$skipped = 0
foreach ($file in $files) {
$extension = $file.Extension.ToLowerInvariant()
if ($extension -notin $allowed) {
continue
}
$relative = $file.FullName.Substring($root.Length) -replace '^[\\/]+', ''
$target = Join-Path $outRoot $relative
if ((Test-Path -LiteralPath $target) -and -not $Force) {
Write-Host "Пропуск: $target"
$skipped++
continue
}
$parent = Split-Path -Parent $target
if (-not (Test-Path -LiteralPath $parent)) {
New-Item -ItemType Directory -Path $parent -Force | Out-Null
}
$image = [System.Drawing.Image]::FromFile($file.FullName)
try {
Apply-Orientation -Image $image -Orientation (Get-Orientation -Image $image)
if ($image.PropertyIdList -contains 274) {
$image.RemovePropertyItem(274)
}
$ratio = [Math]::Min($MaxWidth / $image.Width, $MaxHeight / $image.Height)
if ($ratio -ge 1) {
$ratio = 1
}
$newWidth = [Math]::Max(1, [int][Math]::Round($image.Width * $ratio))
$newHeight = [Math]::Max(1, [int][Math]::Round($image.Height * $ratio))
$pixelFormat = if ($extension -eq '.png') {
[System.Drawing.Imaging.PixelFormat]::Format32bppArgb
}
else {
[System.Drawing.Imaging.PixelFormat]::Format24bppRgb
}
$bitmap = New-Object System.Drawing.Bitmap($newWidth, $newHeight, $pixelFormat)
try {
$graphics = [System.Drawing.Graphics]::FromImage($bitmap)
try {
if ($extension -eq '.png') {
$graphics.Clear([System.Drawing.Color]::Transparent)
}
else {
$graphics.Clear([System.Drawing.Color]::White)
}
$graphics.InterpolationMode = [System.Drawing.Drawing2D.InterpolationMode]::HighQualityBicubic
$graphics.PixelOffsetMode = [System.Drawing.Drawing2D.PixelOffsetMode]::HighQuality
$graphics.SmoothingMode = [System.Drawing.Drawing2D.SmoothingMode]::HighQuality
$graphics.DrawImage($image, 0, 0, $newWidth, $newHeight)
}
finally {
$graphics.Dispose()
}
switch ($extension) {
'.jpg' { Save-Jpeg -Bitmap $bitmap -Target $target -Quality $JpegQuality }
'.jpeg' { Save-Jpeg -Bitmap $bitmap -Target $target -Quality $JpegQuality }
'.png' { $bitmap.Save($target, [System.Drawing.Imaging.ImageFormat]::Png) }
'.bmp' { $bitmap.Save($target, [System.Drawing.Imaging.ImageFormat]::Bmp) }
'.tif' { $bitmap.Save($target, [System.Drawing.Imaging.ImageFormat]::Tiff) }
'.tiff' { $bitmap.Save($target, [System.Drawing.Imaging.ImageFormat]::Tiff) }
}
}
finally {
$bitmap.Dispose()
}
}
finally {
$image.Dispose()
}
Write-Host "Готово: $relative ($newWidth x $newHeight)"
$done++
}
Write-Host "Итог: $done готово, $skipped пропущено"
Скрипты работают с файлами и настройками системы. Перед запуском прочитайте код и проверьте пути. Особенно если скрипт удаляет, перезаписывает или перемещает данные.