[APORTE] [PowerShell] IrfanView | Convert image files to JPG
(1/1)
Eleкtro:
El siguiente script desarrollado en PowerShell y dependiente del programa de terceros IrfanView, sirve para convertir todos los archivos de imagen del directorio actual, a formato JPG.
En la sección "Variables" dentro del script pueden personalizar la calidad de codificación JPG y los tipos de archivos de imagen a procesar entre otras cosas configurables.
Código
<#
===========================================================================================
| |
| Variables |
| |
===========================================================================================
#>
$inputDirectoryPath = "$PSScriptRoot"
$fileNameSearchPattern = "*.*"
$imageExts = @("avif", "bmp", "jp2", "jpg", "png", "tga", "tif", "webp")
$recurse = $false
$irfanviewFullPath = "C:\Program Files\IrfanView\i_view64.exe"
$jpgQuality = 95
$overwriteConfirm = $true
$sendToRecycleBinConvertedFiles = $true
<#
===========================================================================================
| |
| Functions |
| |
===========================================================================================
#>
function Show-WelcomeScreen {
Clear-Host
Write-Host ""
Write-Host " $($host.ui.RawUI.WindowTitle)"
Write-Host " +===========================================+"
Write-Host " | |"
Write-Host " | This script will search for image files |"
Write-Host " | in the current working directory, and use |"
Write-Host " | IrfanView to convert them to JPG format. |"
Write-Host " | |"
Write-Host " +===========================================+"
Write-Host ""
Write-Host " Script Settings " -ForegroundColor DarkGray
Write-Host " ========================" -ForegroundColor DarkGray
Write-Host " Input Directory Path....: $inputDirectoryPath" -ForegroundColor DarkGray
Write-Host " Recursive File Search...: $recurse" -ForegroundColor DarkGray
Write-Host " Search File Name Pattern: $fileNameSearchPattern" -ForegroundColor DarkGray
Write-Host " Search File Extensions..: $($imageExts -join ', ')" -ForegroundColor DarkGray
Write-Host " IrfanView Full Path.....: $irfanviewFullPath" -ForegroundColor DarkGray
Write-Host " JPG Quality.............: $jpgQuality%" -ForegroundColor DarkGray
Write-Host " Confirm Overwrite JPG...: $overwriteConfirm" -ForegroundColor DarkGray
Write-Host " Recycle Converted Files.: $sendToRecycleBinConvertedFiles" -ForegroundColor DarkGray
Write-Host ""
}
function Confirm-Continue {
Write-Host " Press 'Y' key to continue or 'N' to exit."
Write-Host ""
Write-Host " -Continue? (Y/N)"
do {
$key = $Host.UI.RawUI.ReadKey("NoEcho,IncludeKeyDown")
$char = $key.Character.ToString().ToUpper()
if ($char -ne "Y" -and $char -ne "N") {
[console]::beep(1500, 500)
}
} while ($char -ne "Y" -and $char -ne "N")
if ($char -eq "N") {Exit(1)}
}
function Validate-Parameters {
if (-not (Test-Path -LiteralPath $inputDirectoryPath -PathType Container)) {
Write-Host " Input directory path does not exists!" -BackgroundColor Black -ForegroundColor Red
Write-Host ""
Write-Host " Press any key to exit..."
$key = $Host.UI.RawUI.ReadKey("NoEcho, IncludeKeyDown")
Exit(1)
}
if (-not (Test-Path -LiteralPath $irfanviewFullPath -PathType Leaf)) {
Write-Host " Irfanview file path does not exists!" -BackgroundColor Black -ForegroundColor Red
Write-Host ""
Write-Host " Press any key to exit..."
$key = $Host.UI.RawUI.ReadKey("NoEcho, IncludeKeyDown")
Exit(1)
}
if ($imageExts.Count -eq 0) {
Write-Host " No image file extensions were specified!" -BackgroundColor Black -ForegroundColor Red
Write-Host ""
Write-Host " Press any key to exit..."
$key = $Host.UI.RawUI.ReadKey("NoEcho, IncludeKeyDown")
Exit(1)
}
}
function Convert-Files {
Clear-Host
Add-Type -AssemblyName Microsoft.VisualBasic
$imageFiles = $null
if ($recurse) {
$imageFiles = Get-ChildItem -LiteralPath $inputDirectoryPath -Filter $fileNameSearchPattern -Recurse | Where-Object { $imageExts -contains $_.Extension.ToLower().TrimStart('.') }
} else {
$imageFiles = Get-ChildItem -LiteralPath $inputDirectoryPath -Filter $fileNameSearchPattern | Where-Object { $imageExts -contains $_.Extension.ToLower().TrimStart('.') }
}
foreach ($imageFile in $imageFiles) {
Write-Host " Converting to JPG: $($imageFile.FullName.Replace($inputDirectoryPath, "."))"
$fileNameWithoutExtension = [System.IO.Path]::GetFileNameWithoutExtension($imageFile.Name)
$outputFilePath = Join-Path -Path ($imageFile.Directory.FullName) -ChildPath "$fileNameWithoutExtension.jpg"
if ((Test-Path -LiteralPath $outputFilePath -PathType Leaf) -and ($overwriteConfirm)) {
# El archivo no existe o no se debe sobrescribir
Write-Warning " Output JPG file already exists but `$overwriteConfirm variable is disabled."
Write-Warning " The output JPG file will be overwitten if you continue."
Write-Host ""
Confirm-Continue
Write-Host ""
}
$exitCode = $null
try {
$procStartInfo = New-Object System.Diagnostics.ProcessStartInfo
$procStartInfo.FileName = $irfanviewFullPath
$procStartInfo.Arguments = "`"$($imageFile.FullName)`" /jpgq=$jpgQuality /convert=`"$outputFilePath`""
$procStartInfo.UseShellExecute = $false
$process = New-Object System.Diagnostics.Process
$process.StartInfo = $procStartInfo
$process.Start() | Out-Null
$process.WaitForExit()
$exitCode = $process.ExitCode
} catch {
Write-Host ""
Write-Host " Error running IrfanView process." -BackgroundColor Black -ForegroundColor Red
Write-Host ""
Write-Error -Message ($_.Exception.Message)
Write-Host ""
Write-Host " Press any key to exit..."
$key = $Host.UI.RawUI.ReadKey("NoEcho, IncludeKeyDown")
Exit(1)
}
if ($exitCode -eq 0) {
Write-Host " File converted successfully." -ForegroundColor DarkGreen
if ($sendToRecycleBinConvertedFiles) {
[Microsoft.VisualBasic.FileIO.FileSystem]::DeleteFile($imageFile.FullName, 'OnlyErrorDialogs', 'SendToRecycleBin')
Write-Host " File sent to recycle bin." -ForegroundColor DarkGray
}
Write-Host ""
} else {
Write-Host " Error converting file to JPG. IrfanView Exit Code: $exitCode" -BackgroundColor Black -ForegroundColor Red
Write-Host ""
}
}
}
function Show-GoodbyeScreen {
Write-Host " Operation Completed!" -BackgroundColor Black -ForegroundColor Green
Write-Host ""
Write-Host " Press any key to exit..."
$key = $Host.UI.RawUI.ReadKey("NoEcho, IncludeKeyDown")
Exit(0)
}
<#
===========================================================================================
| |
| Main |
| |
===========================================================================================
#>
[System.Console]::Title = "Convert image files to JPG - by Elektro"
#[System.Console]::SetWindowSize(146, 27)
[CultureInfo]::CurrentUICulture = "en-US"
try { Set-ExecutionPolicy -ExecutionPolicy "Unrestricted" -Scope "Process" } catch { }
Show-WelcomeScreen
Validate-Parameters
Confirm-Continue
Convert-Files
Show-GoodbyeScreen
Navegación