elhacker.net cabecera Bienvenido(a), Visitante. Por favor Ingresar o Registrarse
¿Perdiste tu email de activación?.

 

 


Tema destacado: (TUTORIAL) Aprende a emular Sentinel Dongle By Yapis


+  Foro de elhacker.net
|-+  Programación
| |-+  Scripting
| | |-+  [APORTE] [PowerShell] IrfanView | Convert image files to JPG
0 Usuarios y 1 Visitante están viendo este tema.
Páginas: [1] Ir Abajo Respuesta Imprimir
Autor Tema: [APORTE] [PowerShell] IrfanView | Convert image files to JPG  (Leído 956 veces)
Eleкtro
Ex-Staff
*
Desconectado Desconectado

Mensajes: 9.878



Ver Perfil
[APORTE] [PowerShell] IrfanView | Convert image files to JPG
« en: 4 Marzo 2024, 14:45 pm »

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
  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. $jpgQuality = 95
  16. $overwriteConfirm = $true
  17. $sendToRecycleBinConvertedFiles = $true
  18.  
  19. <#
  20. ===========================================================================================
  21. |                                                                                         |
  22. |                                    Functions                                            |
  23. |                                                                                         |
  24. ===========================================================================================
  25. #>
  26.  
  27. function Show-WelcomeScreen {
  28.    Clear-Host
  29.    Write-Host ""
  30.    Write-Host " $($host.ui.RawUI.WindowTitle)"
  31.    Write-Host " +===========================================+"
  32.    Write-Host " |                                           |"
  33.    Write-Host " | This script will search for image files   |"
  34.    Write-Host " | in the current working directory, and use |"
  35.    Write-Host " | IrfanView to convert them to JPG format.  |"
  36.    Write-Host " |                                           |"
  37.    Write-Host " +===========================================+"
  38.    Write-Host ""
  39.    Write-Host " Script Settings         " -ForegroundColor DarkGray
  40.    Write-Host " ========================" -ForegroundColor DarkGray
  41.    Write-Host " Input Directory Path....: $inputDirectoryPath" -ForegroundColor DarkGray
  42.    Write-Host " Recursive File Search...: $recurse" -ForegroundColor DarkGray
  43.    Write-Host " Search File Name Pattern: $fileNameSearchPattern" -ForegroundColor DarkGray
  44.    Write-Host " Search File Extensions..: $($imageExts -join ', ')" -ForegroundColor DarkGray
  45.    Write-Host " IrfanView Full Path.....: $irfanviewFullPath" -ForegroundColor DarkGray
  46.    Write-Host " JPG Quality.............: $jpgQuality%" -ForegroundColor DarkGray
  47.    Write-Host " Confirm Overwrite JPG...: $overwriteConfirm" -ForegroundColor DarkGray
  48.    Write-Host " Recycle Converted Files.: $sendToRecycleBinConvertedFiles" -ForegroundColor DarkGray
  49.    Write-Host ""
  50. }
  51.  
  52. function Confirm-Continue {
  53.    Write-Host " Press 'Y' key to continue or 'N' to exit."
  54.    Write-Host ""
  55.    Write-Host " -Continue? (Y/N)"
  56.    do {
  57.        $key = $Host.UI.RawUI.ReadKey("NoEcho,IncludeKeyDown")
  58.        $char = $key.Character.ToString().ToUpper()
  59.        if ($char -ne "Y" -and $char -ne "N") {
  60.            [console]::beep(1500, 500)
  61.        }
  62.    } while ($char -ne "Y" -and $char -ne "N")
  63.    if ($char -eq "N") {Exit(1)}
  64. }
  65.  
  66. function Validate-Parameters {
  67.  
  68.    if (-not (Test-Path -LiteralPath $inputDirectoryPath -PathType Container)) {
  69.        Write-Host " Input directory path does not exists!" -BackgroundColor Black -ForegroundColor Red
  70.        Write-Host ""
  71.        Write-Host " Press any key to exit..."
  72.        $key = $Host.UI.RawUI.ReadKey("NoEcho, IncludeKeyDown")
  73.        Exit(1)
  74.    }
  75.  
  76.    if (-not (Test-Path -LiteralPath $irfanviewFullPath -PathType Leaf)) {
  77.        Write-Host " Irfanview file path does not exists!" -BackgroundColor Black -ForegroundColor Red
  78.        Write-Host ""
  79.        Write-Host " Press any key to exit..."
  80.        $key = $Host.UI.RawUI.ReadKey("NoEcho, IncludeKeyDown")
  81.        Exit(1)
  82.    }
  83.  
  84.    if ($imageExts.Count -eq 0) {
  85.        Write-Host " No image file extensions were specified!" -BackgroundColor Black -ForegroundColor Red
  86.        Write-Host ""
  87.        Write-Host " Press any key to exit..."
  88.        $key = $Host.UI.RawUI.ReadKey("NoEcho, IncludeKeyDown")
  89.        Exit(1)
  90.    }
  91.  
  92. }
  93.  
  94. function Convert-Files {
  95.    Clear-Host
  96.    Add-Type -AssemblyName Microsoft.VisualBasic
  97.  
  98.    $imageFiles = $null
  99.    if ($recurse) {
  100.        $imageFiles = Get-ChildItem -LiteralPath $inputDirectoryPath -Filter $fileNameSearchPattern -Recurse | Where-Object { $imageExts -contains $_.Extension.ToLower().TrimStart('.') }
  101.    } else {
  102.        $imageFiles = Get-ChildItem -LiteralPath $inputDirectoryPath -Filter $fileNameSearchPattern | Where-Object { $imageExts -contains $_.Extension.ToLower().TrimStart('.') }
  103.    }
  104.  
  105.    foreach ($imageFile in $imageFiles) {
  106.        Write-Host " Converting to JPG: $($imageFile.FullName.Replace($inputDirectoryPath, "."))"
  107.  
  108.        $fileNameWithoutExtension = [System.IO.Path]::GetFileNameWithoutExtension($imageFile.Name)
  109.        $outputFilePath = Join-Path -Path ($imageFile.Directory.FullName) -ChildPath "$fileNameWithoutExtension.jpg"
  110.  
  111.        if ((Test-Path -LiteralPath $outputFilePath -PathType Leaf) -and ($overwriteConfirm)) {
  112.            # El archivo no existe o no se debe sobrescribir
  113.            Write-Warning " Output JPG file already exists but `$overwriteConfirm variable is disabled."
  114.            Write-Warning " The output JPG file will be overwitten if you continue."
  115.            Write-Host ""
  116.            Confirm-Continue
  117.            Write-Host ""
  118.        }
  119.  
  120.        $exitCode = $null
  121.        try {
  122.            $procStartInfo = New-Object System.Diagnostics.ProcessStartInfo
  123.            $procStartInfo.FileName = $irfanviewFullPath
  124.            $procStartInfo.Arguments = "`"$($imageFile.FullName)`" /jpgq=$jpgQuality /convert=`"$outputFilePath`""
  125.            $procStartInfo.UseShellExecute = $false
  126.            $process = New-Object System.Diagnostics.Process
  127.            $process.StartInfo = $procStartInfo
  128.            $process.Start() | Out-Null
  129.            $process.WaitForExit()
  130.            $exitCode = $process.ExitCode
  131.        } catch {
  132.            Write-Host ""
  133.            Write-Host " Error running IrfanView process." -BackgroundColor Black -ForegroundColor Red
  134.            Write-Host ""
  135.            Write-Error -Message ($_.Exception.Message)
  136.            Write-Host ""
  137.            Write-Host " Press any key to exit..."
  138.            $key = $Host.UI.RawUI.ReadKey("NoEcho, IncludeKeyDown")
  139.            Exit(1)
  140.        }
  141.  
  142.        if ($exitCode -eq 0) {
  143.            Write-Host " File converted successfully." -ForegroundColor DarkGreen
  144.            if ($sendToRecycleBinConvertedFiles) {
  145.                [Microsoft.VisualBasic.FileIO.FileSystem]::DeleteFile($imageFile.FullName, 'OnlyErrorDialogs', 'SendToRecycleBin')
  146.                Write-Host " File sent to recycle bin." -ForegroundColor DarkGray
  147.            }
  148.            Write-Host ""
  149.        } else {
  150.            Write-Host " Error converting file to JPG. IrfanView Exit Code: $exitCode" -BackgroundColor Black -ForegroundColor Red
  151.            Write-Host ""
  152.        }
  153.    }
  154. }
  155.  
  156. function Show-GoodbyeScreen {
  157.    Write-Host " Operation Completed!" -BackgroundColor Black -ForegroundColor Green
  158.    Write-Host ""
  159.    Write-Host " Press any key to exit..."
  160.    $key = $Host.UI.RawUI.ReadKey("NoEcho, IncludeKeyDown")
  161.    Exit(0)
  162. }
  163.  
  164. <#
  165. ===========================================================================================
  166. |                                                                                         |
  167. |                                         Main                                            |
  168. |                                                                                         |
  169. ===========================================================================================
  170. #>
  171.  
  172. [System.Console]::Title = "Convert image files to JPG - by Elektro"
  173. #[System.Console]::SetWindowSize(146, 27)
  174. [CultureInfo]::CurrentUICulture = "en-US"
  175.  
  176. try { Set-ExecutionPolicy -ExecutionPolicy "Unrestricted" -Scope "Process" } catch { }
  177.  
  178. Show-WelcomeScreen
  179. Validate-Parameters
  180. Confirm-Continue
  181. Convert-Files
  182. Show-GoodbyeScreen
  183.  
  184.  


« Última modificación: 4 Marzo 2024, 14:48 pm por Eleкtro » En línea



Páginas: [1] Ir Arriba Respuesta Imprimir 

Ir a:  

Mensajes similares
Asunto Iniciado por Respuestas Vistas Último mensaje
[APORTE] [PowerShell] 3rd Party Driver Backup Tool
Scripting
Eleкtro 3 2,096 Último mensaje 4 Marzo 2024, 01:07 am
por Danielㅤ
[APORTE] [PowerShell] Truncate Log Files
Scripting
Eleкtro 0 1,123 Último mensaje 3 Marzo 2024, 22:14 pm
por Eleкtro
[APORTE] [PowerShell] ImageMagick | Convert image files to ICO
Scripting
Eleкtro 0 1,197 Último mensaje 4 Marzo 2024, 14:41 pm
por Eleкtro
[APORTE] [PowerShell] IrfanView | Crop image files
Scripting
Eleкtro 0 1,089 Último mensaje 4 Marzo 2024, 14:48 pm
por Eleкtro
[APORTE] [PowerShell] RAR.exe | Test RAR Files
Scripting
Eleкtro 0 7,206 Último mensaje 5 Abril 2024, 00:39 am
por Eleкtro
WAP2 - Aviso Legal - Powered by SMF 1.1.21 | SMF © 2006-2008, Simple Machines