Foro de elhacker.net

Programación => Scripting => Mensaje iniciado por: Eleкtro en 4 Marzo 2024, 14:48 pm



Título: [APORTE] [PowerShell] IrfanView | Crop image files
Publicado por: Eleкtro en 4 Marzo 2024, 14:48 pm
El siguiente script desarrollado en PowerShell y dependiente del programa de terceros IrfanView, sirve para hacer un recorte (crop) específico en los archivos de imagen del directorio actual.

En la sección "Variables" dentro del script pueden personalizar los puntos de recorte (x, y, width, height), así como la calidad de codificación para archivos JPG entre otras cosas configurables.

(http://i.imgur.com/xZ2IZOyl.png) (https://i.imgur.com/xZ2IZOy.png)



Código
  1. <#
  2. ===========================================================================================
  3. |                                                                                         |
  4. |                                        Variables                                        |
  5. |                                                                                         |
  6. ===========================================================================================
  7. #>
  8.  
  9. $inputDirectoryPath = "$PSScriptRoot"
  10. $fileNameSearchPattern = "*.*"
  11. $imageExts = @("avif", "bmp", "jp2", "jpg", "png", "tga", "tif", "webp")
  12. $recurse = $false
  13.  
  14. $irfanviewFullPath = "C:\Program Files\IrfanView\i_view64.exe"
  15.  
  16. # Cropping values
  17. $x      = 12
  18. $y      = 20
  19. $width  = 620
  20. $height = 560
  21.  
  22. # For cropping images that are jpg/jpeg
  23. $jpgQuality = 95
  24.  
  25.  
  26. <#
  27. ===========================================================================================
  28. |                                                                                         |
  29. |                                    Functions                                            |
  30. |                                                                                         |
  31. ===========================================================================================
  32. #>
  33.  
  34. function Show-WelcomeScreen {
  35.    Clear-Host
  36.    Write-Host ""
  37.    Write-Host " $($host.ui.RawUI.WindowTitle)"
  38.    Write-Host " +=========================================+"
  39.    Write-Host " |                                         |"
  40.    Write-Host " | This script will search for image files |"
  41.    Write-Host " | in the current working directory, and   |"
  42.    Write-Host " | use IrfanView to crop them using the    |"
  43.    Write-Host " | specified cropping settings.            |"
  44.    Write-Host " |                                         |"
  45.    Write-Host " +=========================================+"
  46.    Write-Host ""
  47.    Write-Host " Script Settings         " -ForegroundColor DarkGray
  48.    Write-Host " ========================" -ForegroundColor DarkGray
  49.    Write-Host " Input Directory Path....: $inputDirectoryPath" -ForegroundColor DarkGray
  50.    Write-Host " Recursive File Search...: $recurse" -ForegroundColor DarkGray
  51.    Write-Host " Search File Name Pattern: $fileNameSearchPattern" -ForegroundColor DarkGray
  52.    Write-Host " Search File Extensions..: $($imageExts -join ', ')" -ForegroundColor DarkGray
  53.    Write-Host " IrfanView Full Path.....: $irfanviewFullPath" -ForegroundColor DarkGray
  54.    Write-Host " JPG Quality.............: $jpgQuality%" -ForegroundColor DarkGray
  55.    Write-Host " Cropping.values.........: X=$x, Y=$y, Width=$width, Height=$height" -ForegroundColor DarkGray
  56.    Write-Host ""
  57. }
  58.  
  59. function Confirm-Continue {
  60.    Write-Host " Press 'Y' key to continue or 'N' to exit."
  61.    Write-Host ""
  62.    Write-Host " -Continue? (Y/N)"
  63.    do {
  64.        $key = $Host.UI.RawUI.ReadKey("NoEcho,IncludeKeyDown")
  65.        $char = $key.Character.ToString().ToUpper()
  66.        if ($char -ne "Y" -and $char -ne "N") {
  67.            [console]::beep(1500, 500)
  68.        }
  69.    } while ($char -ne "Y" -and $char -ne "N")
  70.    if ($char -eq "N") {Exit(1)}
  71. }
  72.  
  73. function Validate-Parameters {
  74.  
  75.    if (-not (Test-Path -LiteralPath $inputDirectoryPath -PathType Container)) {
  76.        Write-Host " Input directory path does not exists!" -BackgroundColor Black -ForegroundColor Red
  77.        Write-Host ""
  78.        Write-Host " Press any key to exit..."
  79.        $key = $Host.UI.RawUI.ReadKey("NoEcho, IncludeKeyDown")
  80.        Exit(1)
  81.    }
  82.  
  83.    if (-not (Test-Path -LiteralPath $irfanviewFullPath -PathType Leaf)) {
  84.        Write-Host " Irfanview file path does not exists!" -BackgroundColor Black -ForegroundColor Red
  85.        Write-Host ""
  86.        Write-Host " Press any key to exit..."
  87.        $key = $Host.UI.RawUI.ReadKey("NoEcho, IncludeKeyDown")
  88.        Exit(1)
  89.    }
  90.  
  91.    if ($imageExts.Count -eq 0) {
  92.        Write-Host " No image file extensions were specified!" -BackgroundColor Black -ForegroundColor Red
  93.        Write-Host ""
  94.        Write-Host " Press any key to exit..."
  95.        $key = $Host.UI.RawUI.ReadKey("NoEcho, IncludeKeyDown")
  96.        Exit(1)
  97.    }
  98.  
  99. }
  100.  
  101. function Crop-Files {
  102.    Clear-Host
  103.  
  104.    $imageFiles = $null
  105.    if ($recurse) {
  106.        $imageFiles = Get-ChildItem -LiteralPath $inputDirectoryPath -Filter $fileNameSearchPattern -Recurse | Where-Object { $imageExts -contains $_.Extension.ToLower().TrimStart('.') }
  107.    } else {
  108.        $imageFiles = Get-ChildItem -LiteralPath $inputDirectoryPath -Filter $fileNameSearchPattern | Where-Object { $imageExts -contains $_.Extension.ToLower().TrimStart('.') }
  109.    }
  110.  
  111.    foreach ($imageFile in $imageFiles) {
  112.        Write-Host " Cropping file: $($imageFile.FullName.Replace($inputDirectoryPath, "."))"
  113.  
  114.        $exitCode = $null
  115.        try {
  116.            $process = New-Object System.Diagnostics.Process
  117.            $process.StartInfo.FileName = $irfanviewFullPath
  118.            $process.StartInfo.Arguments = "`"$($imageFile.FullName)`" /crop=($x,$y,$width,$height) /jpgq=$jpgQuality /convert=""$($imageFile.FullName)"""
  119.            $process.StartInfo.UseShellExecute = $false
  120.            $started  = $process.Start() | Out-Null
  121.            $exited   = $process.WaitForExit()
  122.            $exitCode = $process.ExitCode
  123.        } catch {
  124.            Write-Host ""
  125.            Write-Host " Error running IrfanView process." -BackgroundColor Black -ForegroundColor Red
  126.            Write-Host ""
  127.            Write-Error -Message ($_.Exception.Message)
  128.            Write-Host ""
  129.            Write-Host " Press any key to exit..."
  130.            $key = $Host.UI.RawUI.ReadKey("NoEcho, IncludeKeyDown")
  131.            Exit(1)
  132.        }
  133.  
  134.        if ($exitCode -eq 0) {
  135.            Write-Host " File cropped successfully." -ForegroundColor DarkGreen
  136.            Write-Host ""
  137.        } else {
  138.            Write-Host " Error cropping file. IrfanView Exit Code: $exitCode" -BackgroundColor Black -ForegroundColor Red
  139.            Write-Host ""
  140.            Write-Host " Press any key to ignore and continue..."
  141.            $key = $Host.UI.RawUI.ReadKey("NoEcho, IncludeKeyDown")
  142.        }
  143.    }
  144. }
  145.  
  146. function Show-GoodbyeScreen {
  147.    Write-Host " Operation Completed!" -BackgroundColor Black -ForegroundColor Green
  148.    Write-Host ""
  149.    Write-Host " Press any key to exit..."
  150.    $key = $Host.UI.RawUI.ReadKey("NoEcho, IncludeKeyDown")
  151.    Exit(0)
  152. }
  153.  
  154. <#
  155. ===========================================================================================
  156. |                                                                                         |
  157. |                                         Main                                            |
  158. |                                                                                         |
  159. ===========================================================================================
  160. #>
  161.  
  162. [System.Console]::Title = "Crop image files - by Elektro"
  163. #[System.Console]::SetWindowSize(146, 27)
  164. [CultureInfo]::CurrentUICulture = "en-US"
  165.  
  166. try { Set-ExecutionPolicy -ExecutionPolicy "Unrestricted" -Scope "Process" } catch { }
  167.  
  168. Show-WelcomeScreen
  169. Validate-Parameters
  170. Confirm-Continue
  171. Crop-Files
  172. Show-GoodbyeScreen
  173.