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

 

 


Tema destacado: Entrar al Canal Oficial Telegram de elhacker.net


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

Mensajes: 9.885



Ver Perfil
[APORTE] [PowerShell] ImageMagick | Convert image files to ICO
« en: 4 Marzo 2024, 14:41 pm »

El siguiente script desarrollado en PowerShell y dependiente del programa de terceros ImageMagick, sirve para convertir todos los archivos de imagen del directorio actual, a formato ICO. Soportando transparencia.

En la sección "Variables" dentro del script pueden personalizar los tamaños de las capas del icono, la calidad, y el color usado como transparencia entre otras cosas configurables.





Código
  1. <#
  2. ===========================================================================================
  3. |                                                                                         |
  4. |                                        Variables                                        |
  5. |                                                                                         |
  6. ===========================================================================================
  7. #>
  8.  
  9. $inputDirectoryPath = "$PSScriptRoot"
  10. $recurse = $true
  11. $fileSearchExts = @("avif", "bmp", "jp2", "jpg", "jpeg", "png", "tga", "tif", "webp")
  12. $fileNameSearchPattern = "*.*"
  13. #$fileNameSearchPattern = "Cover.*"
  14.  
  15. $iconSizes     = @(256, 128, 96, 64, 48, 32, 24, 16)
  16. $iconBackColor = "transparent"
  17. $iconQuality   = 100
  18.  
  19. $imageMagickFullPath = "$PSScriptRoot\magick.exe"
  20.  
  21. $imageMagickArgs     = @("-define icon:auto-resize=`"$($iconSizes -join ',')`"",
  22.                         "-background $iconBackColor",
  23.                         "-gravity center",
  24.                         "-extent 1:1#",
  25.                         "-quality $iconQuality"
  26.                        )
  27.  
  28. $overwriteConfirm = $true
  29. $sendToRecycleBinConvertedFiles = $false
  30.  
  31. <#
  32. ===========================================================================================
  33. |                                                                                         |
  34. |                                    Functions                                            |
  35. |                                                                                         |
  36. ===========================================================================================
  37. #>
  38.  
  39. function Show-WelcomeScreen {
  40.    Clear-Host
  41.    Write-Host ""
  42.    Write-Host " $($host.ui.RawUI.WindowTitle)"
  43.    Write-Host " +=============================================+"
  44.    Write-Host " |                                            |"
  45.    Write-Host " | This script will search for image files    |"
  46.    Write-Host " | in the current working directory, and use  |"
  47.    Write-Host " | ImageMagick to convert them to ICO format. |"
  48.    Write-Host " |                                            |"
  49.    Write-Host " +============================================+"
  50.    Write-Host ""
  51.    Write-Host " Script Settings         " -ForegroundColor DarkGray
  52.    Write-Host " ========================" -ForegroundColor DarkGray
  53.    Write-Host " Input Directory Path....: $inputDirectoryPath" -ForegroundColor DarkGray
  54.    Write-Host " Recursive File Search...: $recurse" -ForegroundColor DarkGray
  55.    Write-Host " Search File Name Pattern: $fileNameSearchPattern" -ForegroundColor DarkGray
  56.    Write-Host " Search File Extensions..: $($fileSearchExts -join ', ')" -ForegroundColor DarkGray
  57.    Write-Host " ImageMagick Full Path...: $imageMagickFullPath" -ForegroundColor DarkGray
  58.    Write-Host " Icon Sizes (and order)..: $($iconSizes -join ', ')" -ForegroundColor DarkGray
  59.    Write-Host " Icon Background Color...: $iconBackColor" -ForegroundColor DarkGray
  60.    Write-Host " Icon Quality............: $iconQuality" -ForegroundColor DarkGray
  61.    Write-Host " Confirm Overwrite ICO...: $overwriteConfirm" -ForegroundColor DarkGray
  62.    Write-Host " Recycle Converted Files.: $sendToRecycleBinConvertedFiles" -ForegroundColor DarkGray
  63.    # Write-Host " ImageMagick Arguments...: $($imageMagickArgs -join $([Environment]::NewLine) + '                           ')" -ForegroundColor DarkGray
  64.    Write-Host ""
  65. }
  66.  
  67. function Confirm-Continue {
  68.    Write-Host " Press 'Y' key to continue or 'N' to exit."
  69.    Write-Host ""
  70.    Write-Host " -Continue? (Y/N)"
  71.    do {
  72.        $key = $Host.UI.RawUI.ReadKey("NoEcho,IncludeKeyDown")
  73.        $char = $key.Character.ToString().ToUpper()
  74.        if ($char -ne "Y" -and $char -ne "N") {
  75.            [console]::beep(1500, 500)
  76.        }
  77.    } while ($char -ne "Y" -and $char -ne "N")
  78.    if ($char -eq "N") {Exit(1)}
  79. }
  80.  
  81. function Validate-Parameters {
  82.  
  83.    if (-not (Test-Path -LiteralPath $inputDirectoryPath -PathType Container)) {
  84.        Write-Host " Input directory 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 (-not (Test-Path -LiteralPath $imageMagickFullPath -PathType Leaf)) {
  92.        Write-Host " ImageMagick file path does not exists!" -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.    if ([string]::IsNullOrEmpty($fileNameSearchPattern)) {
  100.        Write-Host " `$fileNameSearchPattern variable is null!" -BackgroundColor Black -ForegroundColor Red
  101.        Write-Host ""
  102.        Write-Host " Press any key to exit..."
  103.        $key = $Host.UI.RawUI.ReadKey("NoEcho, IncludeKeyDown")
  104.        Exit(1)
  105.    }
  106.  
  107.    if ($fileSearchExts.Count -eq 0) {
  108.        Write-Host " No image file extensions were specified!" -BackgroundColor Black -ForegroundColor Red
  109.        Write-Host ""
  110.        Write-Host " Press any key to exit..."
  111.        $key = $Host.UI.RawUI.ReadKey("NoEcho, IncludeKeyDown")
  112.        Exit(1)
  113.    }
  114.  
  115. }
  116.  
  117. function Convert-Files {
  118.    Clear-Host
  119.    Add-Type -AssemblyName Microsoft.VisualBasic
  120.  
  121.    $imageFiles = $null
  122.    if ($recurse) {
  123.        $imageFiles = Get-ChildItem -LiteralPath $inputDirectoryPath -Filter $fileNameSearchPattern -Recurse | Where-Object { $fileSearchExts -contains $_.Extension.ToLower().TrimStart('.') }
  124.    } else {
  125.        $imageFiles = Get-ChildItem -LiteralPath $inputDirectoryPath -Filter $fileNameSearchPattern | Where-Object { $fileSearchExts -contains $_.Extension.ToLower().TrimStart('.') }
  126.    }
  127.  
  128.    foreach ($imageFile in $imageFiles) {
  129.        Write-Host " Converting to ICO: $($imageFile.FullName.Replace($inputDirectoryPath, "."))"
  130.  
  131.        $fileNameWithoutExtension = [System.IO.Path]::GetFileNameWithoutExtension($imageFile.Name)
  132.        $outputFilePath = Join-Path -Path ($imageFile.Directory.FullName) -ChildPath "$fileNameWithoutExtension.ico"
  133.  
  134.        if ((Test-Path -LiteralPath $outputFilePath -PathType Leaf) -and ($overwriteConfirm)) {
  135.            # El archivo no existe o no se debe sobrescribir
  136.            Write-Warning " Output ICO file already exists but `$overwriteConfirm variable is disabled."
  137.            Write-Warning " The output ICO file will be overwitten if you continue."
  138.            Write-Host ""
  139.            Confirm-Continue
  140.            Write-Host ""
  141.        }
  142.  
  143.        $exitCode = $null
  144.        try {
  145.            $procStartInfo = New-Object System.Diagnostics.ProcessStartInfo
  146.            $procStartInfo.FileName = $imageMagickFullPath
  147.            $procStartInfo.Arguments = "`"$($imageFile.FullName)`" $($imageMagickArgs -join ' ') `"$outputFilePath`""
  148.            $procStartInfo.UseShellExecute = $false
  149.            $process = New-Object System.Diagnostics.Process
  150.            $process.StartInfo = $procStartInfo
  151.            $process.Start() | Out-Null
  152.            $process.WaitForExit()
  153.            $exitCode = $process.ExitCode
  154.        } catch {
  155.            Write-Host ""
  156.            Write-Host " Error running ImageMagick process." -BackgroundColor Black -ForegroundColor Red
  157.            Write-Host ""
  158.            Write-Error -Message ($_.Exception.Message)
  159.            Write-Host ""
  160.            Write-Host " Press any key to exit..."
  161.            $key = $Host.UI.RawUI.ReadKey("NoEcho, IncludeKeyDown")
  162.            Exit(1)
  163.        }
  164.  
  165.        if ($exitCode -eq 0) {
  166.            Write-Host " File converted successfully." -ForegroundColor DarkGreen
  167.            if ($sendToRecycleBinConvertedFiles) {
  168.                [Microsoft.VisualBasic.FileIO.FileSystem]::DeleteFile($imageFile.FullName, 'OnlyErrorDialogs', 'SendToRecycleBin')
  169.                Write-Host " File sent to recycle bin." -ForegroundColor DarkGray
  170.            }
  171.            Write-Host ""
  172.        } else {
  173.            Write-Host " Error converting file to ICO. ImageMagick Exit Code: $exitCode" -BackgroundColor Black -ForegroundColor Red
  174.            Write-Host ""
  175.        }
  176.    }
  177. }
  178.  
  179. function Show-GoodbyeScreen {
  180.    Write-Host " Operation Completed!" -BackgroundColor Black -ForegroundColor Green
  181.    Write-Host ""
  182.    Write-Host " Press any key to exit..."
  183.    $key = $Host.UI.RawUI.ReadKey("NoEcho, IncludeKeyDown")
  184.    Exit(0)
  185. }
  186.  
  187. <#
  188. ===========================================================================================
  189. |                                                                                         |
  190. |                                         Main                                            |
  191. |                                                                                         |
  192. ===========================================================================================
  193. #>
  194.  
  195. [System.Console]::Title = "Convert image files to ICO - by Elektro"
  196. #[System.Console]::SetWindowSize(146, 27)
  197. [CultureInfo]::CurrentUICulture = "en-US"
  198.  
  199. try { Set-ExecutionPolicy -ExecutionPolicy "Unrestricted" -Scope "Process" } catch { }
  200.  
  201. Show-WelcomeScreen
  202. Validate-Parameters
  203. Confirm-Continue
  204. Convert-Files
  205. Show-GoodbyeScreen
  206.  


« Última modificación: 4 Marzo 2024, 14:46 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] Windows Event Logs Cleaner
Scripting
Eleкtro 0 1,733 Último mensaje 3 Marzo 2024, 21:54 pm
por Eleкtro
[APORTE] [PowerShell] Truncate Log Files
Scripting
Eleкtro 0 1,188 Último mensaje 3 Marzo 2024, 22:14 pm
por Eleкtro
[APORTE] [PowerShell] IrfanView | Convert image files to JPG
Scripting
Eleкtro 0 1,008 Último mensaje 4 Marzo 2024, 14:45 pm
por Eleкtro
[APORTE] [PowerShell] IrfanView | Crop image files
Scripting
Eleкtro 0 1,179 Último mensaje 4 Marzo 2024, 14:48 pm
por Eleкtro
[APORTE] [PowerShell] RAR.exe | Test RAR Files
Scripting
Eleкtro 0 7,380 Ú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