PowerShell_Scripts/ImageMagick/Convert-WithImageMagick.ps1

88 lines
3.2 KiB
PowerShell
Raw Normal View History

2021-11-15 19:42:46 +00:00
[CmdletBinding(SupportsShouldProcess,ConfirmImpact="Medium")]param(
[Parameter(ParameterSetName="Normal",ValueFromPipeline,ValueFromPipelineByPropertyName)]
[string[]]$ImageMagickPath,
[Parameter(ParameterSetName="Normal",ValueFromPipelineByPropertyName)]
[string]$PageOutputName,
[Parameter(ParameterSetName="Normal")]
[string]$OutputPath,
[Parameter(ParameterSetName="Normal")]
[string]$OutputImageFormat = "png",
[Parameter(ParameterSetName="Normal")]
[string]$OutputImageExtension,
[Parameter(ParameterSetName="Normal")]
[string[]]$MagickArgs,
[Parameter(ParameterSetName="Normal")]
[switch]$Force,
[Parameter(ParameterSetName="Reset")]
[switch]$ResetConfirm
)
BEGIN{
if( $ResetConfirm ) {
Remove-Variable imagemagick_* -Force
Remove-Variable imagemagick_* -Force
return
}
if( -not $OutputImageExtension ) {
$OutputImageExtension = $OutputImageFormat.ToLower()
}
$OutputImageExtension = $OutputImageExtension -replace '\.*(.+)$','.$1'
if( ! (Test-Path variable:global:imagemagick_noToAll) ) {
$imagemagick_noToAll = $PSBoundParameters.ContainsKey('WhatIf');
$imagemagick_yesToAll = $ConfirmPreference -gt 'Low' -and -not $imagemagick_noToAll
}
}
PROCESS{
if( $ResetConfirm ) { return }
$ImageMagickPath | ForEach-Object {
$local:i = [PSCustomObject]@{
ImageMagickPath = $_
PageOutputName = $(
if( $PageOutputName ) {
"$($PageOutputName)$OutputImageExtension"
} else {
[System.IO.Path]::GetFileName($_) -replace "(\.[A-Z]+)(?:\[(\d+)\])?$",'_$2.' -replace '_?\.$',$OutputImageExtension
}
)
OutputPath = $OutputPath
}
if( -not $i.OutputPath ) {
$i.OutputPath = Join-Path ([System.IO.Path]::GetDirectoryName($i.ImageMagickPath)) $OutputImageFormat
}
if( !$imagemagick_noToAll ) { try {
if( -not (Test-Path -LiteralPath $i.OutputPath) ) {
if( $Force ) {
New-Item -ItemType Directory -Path $i.OutputPath -Force
} else {
throw "Output directory $($i.OutputPath) does not exist!"
}
}
} catch {
Write-Error $_
$imagemagick_noToAll = $true
return
}}
$local:outFilePath = Join-Path $i.OutputPath $i.PageOutputName
$local:magickCmdLine=@("convert",$i.ImageMagickPath)+$MagickArgs+@($outFilePath) | Where-Object {$_}
Write-Verbose "$(if( $imagemagick_noToAll ) { "Skipping" } else {"Running"} ): & magick $magickCmdLine"
if( $PSCmdlet.ShouldContinue( "Convert", "$($i.ImageMagickPath) to $outFilePath", [ref]$imagemagick_yesToAll, [ref]$imagemagick_noToAll ) ) {
& magick $magickCmdLine
Write-Verbose "Error state: $?"
if( $? -and (Test-Path $outFilePath) ) {
Get-Item $outFilePath
}
}
}
}
END{
if( $ResetConfirm ) { return }
$global:imagemagick_yesToAll = $imagemagick_yesToAll
$global:imagemagick_noToAll = $imagemagick_noToAll
}