[APORTE] [PowerShell] ImageMagick | Convert image files to ICO

(1/1)

Eleкtro:
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
<#
===========================================================================================
|                                                                                         |
|                                        Variables                                        |
|                                                                                         |
===========================================================================================
#>
 
$inputDirectoryPath = "$PSScriptRoot"
$recurse = $true
$fileSearchExts = @("avif", "bmp", "jp2", "jpg", "jpeg", "png", "tga", "tif", "webp")
$fileNameSearchPattern = "*.*"
#$fileNameSearchPattern = "Cover.*"
 
$iconSizes     = @(256, 128, 96, 64, 48, 32, 24, 16)
$iconBackColor = "transparent"
$iconQuality   = 100
 
$imageMagickFullPath = "$PSScriptRoot\magick.exe"
 
$imageMagickArgs     = @("-define icon:auto-resize=`"$($iconSizes -join ',')`"",
                        "-background $iconBackColor",
                        "-gravity center",
                        "-extent 1:1#",
                        "-quality $iconQuality"
                       )
 
$overwriteConfirm = $true
$sendToRecycleBinConvertedFiles = $false
 
<#
===========================================================================================
|                                                                                         |
|                                    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 " | ImageMagick to convert them to ICO 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..: $($fileSearchExts -join ', ')" -ForegroundColor DarkGray
   Write-Host " ImageMagick Full Path...: $imageMagickFullPath" -ForegroundColor DarkGray
   Write-Host " Icon Sizes (and order)..: $($iconSizes -join ', ')" -ForegroundColor DarkGray
   Write-Host " Icon Background Color...: $iconBackColor" -ForegroundColor DarkGray
   Write-Host " Icon Quality............: $iconQuality" -ForegroundColor DarkGray
   Write-Host " Confirm Overwrite ICO...: $overwriteConfirm" -ForegroundColor DarkGray
   Write-Host " Recycle Converted Files.: $sendToRecycleBinConvertedFiles" -ForegroundColor DarkGray
   # Write-Host " ImageMagick Arguments...: $($imageMagickArgs -join $([Environment]::NewLine) + '                           ')" -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 $imageMagickFullPath -PathType Leaf)) {
       Write-Host " ImageMagick 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 ([string]::IsNullOrEmpty($fileNameSearchPattern)) {
       Write-Host " `$fileNameSearchPattern variable is null!" -BackgroundColor Black -ForegroundColor Red
       Write-Host ""
       Write-Host " Press any key to exit..."
       $key = $Host.UI.RawUI.ReadKey("NoEcho, IncludeKeyDown")
       Exit(1)
   }
 
   if ($fileSearchExts.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 { $fileSearchExts -contains $_.Extension.ToLower().TrimStart('.') }
   } else {
       $imageFiles = Get-ChildItem -LiteralPath $inputDirectoryPath -Filter $fileNameSearchPattern | Where-Object { $fileSearchExts -contains $_.Extension.ToLower().TrimStart('.') }
   }
 
   foreach ($imageFile in $imageFiles) {
       Write-Host " Converting to ICO: $($imageFile.FullName.Replace($inputDirectoryPath, "."))"
 
       $fileNameWithoutExtension = [System.IO.Path]::GetFileNameWithoutExtension($imageFile.Name)
       $outputFilePath = Join-Path -Path ($imageFile.Directory.FullName) -ChildPath "$fileNameWithoutExtension.ico"
 
       if ((Test-Path -LiteralPath $outputFilePath -PathType Leaf) -and ($overwriteConfirm)) {
           # El archivo no existe o no se debe sobrescribir
           Write-Warning " Output ICO file already exists but `$overwriteConfirm variable is disabled."
           Write-Warning " The output ICO file will be overwitten if you continue."
           Write-Host ""
           Confirm-Continue
           Write-Host ""
       }
 
       $exitCode = $null
       try {
           $procStartInfo = New-Object System.Diagnostics.ProcessStartInfo
           $procStartInfo.FileName = $imageMagickFullPath
           $procStartInfo.Arguments = "`"$($imageFile.FullName)`" $($imageMagickArgs -join ' ') `"$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 ImageMagick 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 ICO. ImageMagick 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 ICO - 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

[0] Índice de Mensajes