Размыть область на изображении
Затемняет выбранный прямоугольник сильным размытием, чтобы скрыть лицо, номер или личные данные.
Что делает скрипт
Скрипт уменьшает указанную область, а затем растягивает ее обратно с бикубической интерполяцией, получая мягкое размытие. Координаты задаются в пикселях и автоматически ограничиваются размерами кадра. Обработанные копии сохраняются отдельно, оригиналы не меняются.
- Проверьте результат: слишком маленькая область может оставить часть данных видимой.
Быстрый старт
powershell -File Blur-Region.ps1 -Path C:\Photos -OutDir C:\Photos\private -X 100 -Y 80 -Width 300 -Height 200
Скачайте файл, откройте терминал в папке со скриптом и выполните команду. Запускайте в PowerShell 5.1 или PowerShell 7.
Другие варианты
powershell -File Blur-Region.ps1 -Path .\photo.jpg -OutDir .\out -X 120 -Y 90 -Width 400 -Height 250powershell -File Blur-Region.ps1 -Path C:\Scans -OutDir C:\Scans\private -X 50 -Y 50 -Width 600 -Height 300 -Strength 24 -Recurse
Что понадобится
Встроен в Windows 10/11 (PowerShell 5.1)
Blur-Region.ps1
[CmdletBinding()]
param(
[Parameter(Mandatory = $true)]
[string]$Path,
[Parameter(Mandatory = $true)]
[string]$OutDir,
[Parameter(Mandatory = $true)]
[int]$X,
[Parameter(Mandatory = $true)]
[int]$Y,
[Parameter(Mandatory = $true)]
[int]$Width,
[Parameter(Mandatory = $true)]
[int]$Height,
[ValidateRange(2, 64)]
[int]$Strength = 16,
[ValidateRange(1, 100)]
[int]$JpegQuality = 92,
[switch]$Recurse,
[switch]$Force
)
$ErrorActionPreference = 'Stop'
Add-Type -AssemblyName System.Drawing
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()
}
if ($Width -lt 2 -or $Height -lt 2) {
throw 'Ширина и высота области должны быть не меньше 2 пикселей.'
}
$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 {
$orientation = 1
try {
$orientation = [int]$image.GetPropertyItem(274).Value[0]
}
catch {
$orientation = 1
}
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) }
}
if ($image.PropertyIdList -contains 274) {
$image.RemovePropertyItem(274)
}
$regionX = [Math]::Max(0, $X)
$regionY = [Math]::Max(0, $Y)
$regionWidth = [Math]::Min($Width, $image.Width - $regionX)
$regionHeight = [Math]::Min($Height, $image.Height - $regionY)
if ($regionWidth -lt 2 -or $regionHeight -lt 2) {
throw "Область выходит за пределы изображения: $($file.Name)"
}
$bitmap = New-Object System.Drawing.Bitmap($image)
try {
$region = New-Object System.Drawing.Bitmap($regionWidth, $regionHeight)
try {
$regionGraphics = [System.Drawing.Graphics]::FromImage($region)
try {
$sourceRectangle = New-Object System.Drawing.Rectangle($regionX, $regionY, $regionWidth, $regionHeight)
$destinationRectangle = New-Object System.Drawing.Rectangle(0, 0, $regionWidth, $regionHeight)
$regionGraphics.DrawImage(
$image,
$destinationRectangle,
$sourceRectangle,
[System.Drawing.GraphicsUnit]::Pixel
)
}
finally {
$regionGraphics.Dispose()
}
$smallWidth = [Math]::Max(1, [int][Math]::Round($regionWidth / $Strength))
$smallHeight = [Math]::Max(1, [int][Math]::Round($regionHeight / $Strength))
$small = New-Object System.Drawing.Bitmap($smallWidth, $smallHeight)
try {
$smallGraphics = [System.Drawing.Graphics]::FromImage($small)
try {
$smallGraphics.InterpolationMode = [System.Drawing.Drawing2D.InterpolationMode]::HighQualityBilinear
$smallGraphics.DrawImage($region, 0, 0, $smallWidth, $smallHeight)
}
finally {
$smallGraphics.Dispose()
}
$targetGraphics = [System.Drawing.Graphics]::FromImage($bitmap)
try {
$targetGraphics.InterpolationMode = [System.Drawing.Drawing2D.InterpolationMode]::HighQualityBicubic
$blurRectangle = New-Object System.Drawing.Rectangle($regionX, $regionY, $regionWidth, $regionHeight)
$targetGraphics.DrawImage($small, $blurRectangle)
}
finally {
$targetGraphics.Dispose()
}
}
finally {
$small.Dispose()
}
}
finally {
$region.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"
$done++
}
Write-Host "Итог: $done готово, $skipped пропущено"
Скрипты работают с файлами и настройками системы. Перед запуском прочитайте код и проверьте пути. Особенно если скрипт удаляет, перезаписывает или перемещает данные.