Created
May 28, 2021 17:32
-
-
Save mkht/7d91a87caf6e9ad1129df5960653ea84 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function Compress-Png { | |
[CmdletBinding()] | |
param ( | |
[Parameter(Mandatory, Position = 0, ValueFromPipeline)] | |
[string]$InputFile, | |
[Parameter(Mandatory, Position = 1)] | |
[string]$OutFile | |
) | |
begin { | |
$ProcessInfo = New-Object -TypeName System.Diagnostics.ProcessStartInfo | |
$ProcessInfo.CreateNoWindow = $true | |
$ProcessInfo.FileName = 'pngquant.exe' | |
$ProcessInfo.Arguments = '--quality=65-80 --skip-if-larger -' | |
$ProcessInfo.UseShellExecute = $false | |
$ProcessInfo.RedirectStandardInput = $true | |
$ProcessInfo.RedirectStandardOutput = $true | |
} | |
process { | |
$InputFile = $ExecutionContext.SessionState.Path.GetUnresolvedProviderPathFromPSPath($InputFile.Trim()) | |
$OutFile = $ExecutionContext.SessionState.Path.GetUnresolvedProviderPathFromPSPath($OutFile.Trim().TrimEnd([IO.Path]::DirectorySeparatorChar)) | |
if (-not (Test-Path -LiteralPath $InputFile -PathType Leaf)) { | |
Write-Error -Exception ([System.IO.FileNotFoundException]::('The input file is not exist.')) | |
return | |
} | |
$OutputDirectory = Split-Path -Path $OutFile -Parent | |
if (-not (Test-Path -LiteralPath $OutputDirectory -PathType Container)) { | |
$null = New-Item -Path $OutputDirectory -ItemType Directory | |
} | |
try { | |
$Process = [System.Diagnostics.Process]::Start($ProcessInfo) | |
$InputFileStream = [System.IO.File]::Open($InputFile, [System.IO.FileMode]::Open) | |
$InputFileStream.CopyTo($Process.StandardInput.BaseStream) | |
$InputFileStream.Close() | |
$Process.StandardInput.BaseStream.Flush() | |
$OutputFileStream = [System.IO.FileStream]::new($OutFile, [System.IO.FileMode]::Create, [System.IO.FileAccess]::Write) | |
$Process.StandardOutput.BaseStream.CopyTo($OutputFileStream) | |
} | |
catch { | |
Write-Error -Exception $_.Exception | |
} | |
finally { | |
if ($null -ne $InputFileStream) { | |
$InputFileStream.Close() | |
$InputFileStream.Dispose() | |
} | |
if ($null -ne $OutputFileStream) { | |
$OutputFileStream.Close() | |
$OutputFileStream.Dispose() | |
} | |
} | |
} | |
end { | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment