Подготовить обложку альбома
Уменьшает JPEG или PNG до нужного размера и пересохраняет в JPG либо PNG.
Что делает скрипт
Скрипт читает картинку через System.Drawing, вписывает её в квадрат с сохранением пропорций и при необходимости ставит белый фон для JPEG. Поддерживает отдельный файл или папку. Оригиналы не изменяются, результат складывается в covers.
Быстрый старт
powershell -File Convert-AudioCover.ps1 -Path cover.jpg -MaxSize 1000
Скачайте файл, откройте терминал в папке со скриптом и выполните команду. Запускайте в PowerShell 5.1 или PowerShell 7.
Другие варианты
powershell -File Convert-AudioCover.ps1 -Path C:\Music\cover.png -Format jpgpowershell -File Convert-AudioCover.ps1 -Path D:\Artwork -MaxSize 800 -Force
Что понадобится
Встроен в Windows 10/11 (PowerShell 5.1)
Convert-AudioCover.ps1
[CmdletBinding(SupportsShouldProcess = $true)]
param(
[Parameter(Mandatory = $true)]
[string]$Path,
[string]$OutputDirectory,
[ValidateRange(64, 4000)]
[int]$MaxSize = 1000,
[ValidateSet('jpg', 'png')]
[string]$Format = 'jpg',
[switch]$Force
)
$ErrorActionPreference = 'Stop'
Add-Type -AssemblyName System.Drawing
$resolved = Resolve-Path -LiteralPath $Path -ErrorAction Stop
$extensions = @('.jpg', '.jpeg', '.png', '.bmp', '.gif')
if (Test-Path -LiteralPath $resolved.Path -PathType Container) {
$root = $resolved.Path
$files = @(Get-ChildItem -LiteralPath $root -File -Recurse -ErrorAction SilentlyContinue |
Where-Object { $extensions -contains $_.Extension.ToLowerInvariant() })
if (-not $OutputDirectory) { $OutputDirectory = Join-Path $root 'covers' }
} else {
$item = Get-Item -LiteralPath $resolved.Path
if ($extensions -notcontains $item.Extension.ToLowerInvariant()) {
throw "Формат не похож на изображение: $($item.Extension)"
}
$files = @($item)
if (-not $OutputDirectory) {
$OutputDirectory = Join-Path (Split-Path -Parent $item.FullName) 'covers'
}
}
if ($files.Count -eq 0) {
Write-Host 'Изображения не найдены.'
exit 0
}
$outRoot = $ExecutionContext.SessionState.Path.GetUnresolvedProviderPathFromPSPath($OutputDirectory)
New-Item -ItemType Directory -Path $outRoot -Force | Out-Null
$jpegCodec = $null
if ($Format -eq 'jpg') {
$jpegCodec = [System.Drawing.Imaging.ImageCodecInfo]::GetImageEncoders() |
Where-Object { $_.MimeType -eq 'image/jpeg' } |
Select-Object -First 1
if (-not $jpegCodec) { throw 'JPEG-кодек System.Drawing не найден.' }
}
$done = 0
$skipped = 0
$failed = 0
foreach ($file in $files) {
$destination = Join-Path $outRoot ($file.BaseName + '.' + $Format)
if ((Test-Path -LiteralPath $destination) -and -not $Force) {
Write-Host "Пропуск: $destination уже существует"
$skipped++
continue
}
if (-not $PSCmdlet.ShouldProcess($destination, 'Изменить размер обложки')) { continue }
$image = $null
$bitmap = $null
$graphics = $null
$parameters = $null
try {
$image = [System.Drawing.Image]::FromFile($file.FullName)
$scale = [Math]::Min(1.0, $MaxSize / [double][Math]::Max($image.Width, $image.Height))
$width = [int][Math]::Max(1, [Math]::Round($image.Width * $scale))
$height = [int][Math]::Max(1, [Math]::Round($image.Height * $scale))
$bitmap = [System.Drawing.Bitmap]::new($width, $height)
$graphics = [System.Drawing.Graphics]::FromImage($bitmap)
$graphics.InterpolationMode = [System.Drawing.Drawing2D.InterpolationMode]::HighQualityBicubic
$graphics.SmoothingMode = [System.Drawing.Drawing2D.SmoothingMode]::HighQuality
if ($Format -eq 'jpg') {
$graphics.Clear([System.Drawing.Color]::White)
}
$graphics.DrawImage($image, 0, 0, $width, $height)
if ($Format -eq 'jpg') {
$parameters = [System.Drawing.Imaging.EncoderParameters]::new(1)
$quality = [System.Drawing.Imaging.EncoderParameter]::new(
[System.Drawing.Imaging.Encoder]::Quality, [long]90)
$parameters.Param[0] = $quality
$bitmap.Save($destination, $jpegCodec, $parameters)
} else {
$bitmap.Save($destination, [System.Drawing.Imaging.ImageFormat]::Png)
}
Write-Host "Готово: $($file.Name) -> $destination ($width x $height)"
$done++
} catch {
Write-Host "Ошибка: $($file.FullName): $($_.Exception.Message)" -ForegroundColor Red
$failed++
} finally {
if ($parameters) { $parameters.Dispose() }
if ($graphics) { $graphics.Dispose() }
if ($bitmap) { $bitmap.Dispose() }
if ($image) { $image.Dispose() }
}
}
Write-Host "Итог: готово $done, пропущено $skipped, ошибок $failed"
if ($failed -gt 0) { exit 2 }
Скрипты работают с файлами и настройками системы. Перед запуском прочитайте код и проверьте пути. Особенно если скрипт удаляет, перезаписывает или перемещает данные.